Gallery-Archivist/backend/api/posts/views.py

42 lines
1.4 KiB
Python
Raw Normal View History

from rest_framework import generics
2025-02-10 10:16:26 +01:00
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from apps.archive.models import PostModel
from .serializers import PostPreviewSerializer, PostSerializer
2025-02-10 10:16:26 +01:00
class PostListView(generics.ListAPIView):
2025-02-10 10:16:26 +01:00
permission_classes = [IsAuthenticated]
serializer_class = (
PostPreviewSerializer # Each post will be serialized using this serializer
)
2025-02-10 10:16:26 +01:00
def get_queryset(self):
user = self.request.user.userprofile
2025-02-10 10:16:26 +01:00
if user.show_mature:
queryset = PostModel.objects.all()
2025-02-10 10:16:26 +01:00
else:
queryset = PostModel.objects.filter(mature=False)
return queryset.order_by("-date_created")
2025-02-10 10:16:26 +01:00
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)
2025-02-10 10:16:26 +01:00
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()