Search code examples
pythondjangodjango-rest-frameworkdjango-rest-auth

How to list blog posts of a particular user in Django REST Api


How to list blog posts of a particular user.

using ListAPIView, all blog posts are listed. How to list blog posts of a particular user?

views.py

class BlogList(generics.ListAPIView):
    queryset = models.Blog.objects.all()
    serializer_class = serializers.BlogSerializer

serializers.py

class BlogSerializer(serializers.ModelSerializer):

    class Meta:
        fields = ('id', 'user_id', 'title', 'content', 'created_at',)
        model = models.Blog

urls.py

path('', views.BlogList.as_view()),

Solution

  • Which user? current user? Or any other user?

    If any user, current or otherwise, then you can do this:

    class BlogList(generics.ListAPIView):
        serializer_class = serializers.BlogSerializer
    
        def get_queryset(self):
            return Blog.objects.filter(user_id=self.kwargs['user_id'])
    

    And in the urlconf or urls.py:

    # Make sure you are passing the user id in the url.
    # Otherwise the list view will not pick it up.
    path('<int:user_id>', views.BlogList.as_view()),
    

    So a url like this: 'app_name/user_id/' should give you a list of all of the blogs belonging to the user with user_id.

    Also, you can learn a lot more by visiting the page provided by luizbag.