0

I want to create two endpoints /comments/ and /comments/requests/ or something to that effect. The first shows your comments, and the second shows your pending comments (Comments that people sent you that you need to approve). They both work with a comments model. How could I achieve this in Django Rest Framework?

Right now, my view is

class CommentsListview(APIView):
    serializer_class = CommentSerializer
    def get(self, request, format=None):
        comments, _, _, = Comments.get_comment_users(request.user)
        comments_serializer = CommentSerializer(comments, many=True)
        return Response({'comments': comments_serializer.data})

    def requests(sel,f request, format=None):
        _, requests, _ = Comments.get_comment_users(request.user)
        requests_serializer = CommentSerializer(requests, many=True)
        return Response({'requests': requests_serializer.data})

I'd like to allow a user to go to localhost:8000/comments/ to view their comments and localhost:8000/comments/requests/ to view their pending comment requests. Since I haven't been able to figure this out, the only other sollution would be to require the user to switch the behavior of the endpoint using a parameter as a flag /comments/?requests=True but that just seems sloppy.

Reimus Klinsman
  • 898
  • 2
  • 12
  • 23

1 Answers1

1

use list_route decorator and genericviewset

from rest_framework import viewsets
from rest_framework.decorators import list_route

class CommentsListview(viewsets.GenericViewSet):
    serializer_class = CommentSerializer

    def list(self, request, format=None):
        comments, _, _, = Comments.get_comment_users(request.user)
        comments_serializer = CommentSerializer(comments, many=True)
        return Response({'comments': comments_serializer.data})

    @list_route()
    def requests(sel,f request, format=None):
        _, requests, _ = Comments.get_comment_users(request.user)
        requests_serializer = CommentSerializer(requests, many=True)
        return Response({'requests': requests_serializer.data})
  • /comments/ will call list method
  • /comments/requests/ will call requests method

also look at GenericViews and ViewSet docs it might be helpfull

aliva
  • 5,450
  • 1
  • 33
  • 44
  • Awesome, thanks. That works perfectly. Also, there needs to be a change in `urls.py` instead of using `CommentsListview.as_view` you need to use `CommentsListview.as_view({'get': 'list'})` and `CommentsListview.as_view({'get': 'request'})` – Reimus Klinsman May 02 '17 at 23:28
  • please check out [router](http://www.django-rest-framework.org/api-guide/routers/) docs, with viewsets it's simpler to use DRF routers – aliva May 03 '17 at 06:20