from django.db.models import Prefetch from django.shortcuts import get_object_or_404 from django.views.generic import ListView, RedirectView from .models import Category, Link class CategoryList(ListView): model = Category class LinkList(ListView): template_name = "links/link_list.html" paginate_by = 6 def get_queryset(self): category_group = self.kwargs.get("category", None) if category_group: queryset = Category.objects.filter(slug=category_group) else: queryset = Category.objects.filter(parent=None) return queryset.prefetch_related( Prefetch("links", queryset=Link.objects.filter(is_published=True)) ) class LinkRedirectView(RedirectView): def get_redirect_url(self, *args, **kwargs): url = get_object_or_404(Link, title=kwargs["title"]) url.followed += 1 url.save() return url.website