pythondjangorestdjango-rest-frameworkendpoints

Two endpoints for the same resource in django rest framework


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.


Solution

  • 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})
    

    also look at GenericViews and ViewSet docs it might be helpfull