Skip to content

Commit

Permalink
Add query parameter 'sort' for PostViewSet list method to give differ…
Browse files Browse the repository at this point in the history
…ent sorting options
  • Loading branch information
Termuellinator committed Oct 12, 2023
1 parent 379cd00 commit d465379
Showing 1 changed file with 26 additions and 2 deletions.
28 changes: 26 additions & 2 deletions apps/post/api_views.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
from django.db.models import Count
from rest_framework import viewsets
from rest_framework.views import APIView
from rest_framework.response import Response
Expand All @@ -16,18 +17,41 @@ class StandardPostPagination(PageNumberPagination):


class PostViewSet(viewsets.ModelViewSet):
"""Viewset for posts. List is sorted by creation date by default (?sort=new).
Query parameter 'sort' can be set to 'hot' to sort by upvotes
"""
permission_classes = (permissions.AuthorSuperOrReadOnly,)
pagination_class = StandardPostPagination

queryset = (
models.Post.objects
.select_related("user_id", "cat_id")
.prefetch_related("tags")
.all()
.order_by('-created_at'))
.all())

serializer_class = serializers.PostModelSerializer

def list(self, request, *args, **kwargs):
"""Overwrite list method to have different sorting depending on
the queryparameter 'sort'
"""
sort = self.request.GET.get("sort", "new")
if sort == "new":
self.queryset = (models.Post.objects
.select_related("user_id", "cat_id")
.prefetch_related("tags")
.all()
.order_by('-created_at'))
elif sort == "hot":
self.queryset = (models.Post.objects
.select_related("user_id", "cat_id")
.prefetch_related("tags")
.annotate(rating=Count('userUpVotes', distinct=True) -
Count('userDownVotes', distinct=True),
upvotes=Count('userUpVotes'))
.order_by('-rating', '-upvotes'))
return super().list(self, request, *args, **kwargs)


class CategoryViewSet(mixins.DenyDeletionOfDefaultCategoryMixin,
viewsets.ModelViewSet):
Expand Down

0 comments on commit d465379

Please sign in to comment.