[Fixed]-DjangoRestFramework – How to filter ViewSet's object list based on end-users input?

1πŸ‘

βœ…

In your url:

url(r'^/post/(?P<username>\w+)/?$', PostViewSet.as_view({'get': 'list'})),

Then in your PostViewSet, overwrite the get_queryset() method to filter the data by username

class PostViewSet(viewsets.ModelViewSet):
    queryset = Post.objects.order_by('-createdAt')
    serializer_class = PostSerializer
    permission_classes = (IsAuthenticated, IsLikeOrOwnerDeleteOrReadOnly,)

    def get_queryset(self):
        username = self.kwargs['username']
        return Post.objects.filter(username=username)

UPDATE

If you want to keep /post/ endpoint to retrieve all post. Then you need to create an extra view to handle /post/username

class PostsListByUsername(generics.ListAPIView):
    serializer_class = PostSerializer

        def get_queryset(self):
            username = self.kwargs['username']
            return Post.objects.filter(username=username)

Then in your urls.py

url(r'^/post/(?P<username>\w+)/?$', PostsListByUsername.as_view()),

Note:
In your get_serializer_context method, you don’t need to return request, format and view. DRF will append it for you.

def get_serializer_context(self):
        """
        Extra context provided to the serializer class.
        """
        return {
            'location': self.request.user.userextended.location
        }
πŸ‘€levi

Leave a comment