Refactor: to properly use DRFs view functions

This commit is contained in:
Aroy-Art 2025-02-12 12:35:42 +01:00
parent 3d7e25e20c
commit 3657b4423f
Signed by: Aroy
GPG key ID: 583642324A1D2070
3 changed files with 47 additions and 66 deletions

View file

@ -1,34 +1,42 @@
from rest_framework import generics
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.permissions import IsAuthenticated
from apps.archive.models import PostModel
from .serializers import PostListSerializer, PostSerializer
from .serializers import PostPreviewSerializer, PostSerializer
class PostListView(APIView):
class PostListView(generics.ListAPIView):
permission_classes = [IsAuthenticated]
serializer_class = (
PostPreviewSerializer # Each post will be serialized using this serializer
)
def get(self, request):
user = request.user.userprofile
def get_queryset(self):
user = self.request.user.userprofile
if user.show_mature:
posts = PostModel.objects.all().order_by("-date_created")
queryset = PostModel.objects.all()
else:
posts = PostModel.objects.filter(mature=False).order_by("-date_created")
serializer = PostListSerializer(posts)
return Response(serializer.data)
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 PostView(APIView):
class PostDetailView(generics.RetrieveAPIView):
permission_classes = [IsAuthenticated]
def get(self, request, post_id):
try:
post_instance = PostModel.objects.get(post_id=post_id)
except PostModel.DoesNotExist:
raise NotFound(detail="Post not found.")
serializer = PostSerializer(post_instance)
return Response(serializer.data)
serializer_class = PostSerializer
lookup_field = (
"post_id" # This tells DRF to use the "post_id" URL kwarg for lookups.
)
queryset = PostModel.objects.all()