from rest_framework import generics from rest_framework.response import Response from rest_framework.permissions import IsAuthenticated from apps.archive.models import PostModel from .serializers import PostPreviewSerializer, PostSerializer class PostListView(generics.ListAPIView): permission_classes = [IsAuthenticated] serializer_class = ( PostPreviewSerializer # Each post will be serialized using this serializer ) def get_queryset(self): user = self.request.user.userprofile if user.show_mature: queryset = PostModel.objects.all() else: queryset = PostModel.objects.filter(mature=False) return queryset.order_by("-date_created") def list(self, request, *args, **kwargs): """ Overriding list() allows us to return a custom response structure, for example including a count and a key 'posts' instead of DRF's default 'results'. """ queryset = self.filter_queryset(self.get_queryset()) serializer = self.get_serializer(queryset, many=True) data = {"count": queryset.count(), "posts": serializer.data} return Response(data) class PostDetailView(generics.RetrieveAPIView): permission_classes = [IsAuthenticated] serializer_class = PostSerializer lookup_field = ( "post_id" # This tells DRF to use the "post_id" URL kwarg for lookups. ) queryset = PostModel.objects.all()