Rupesh
Rupesh

Reputation: 101

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()),

Upvotes: 1

Views: 2046

Answers (2)

Mohammad Abouchama
Mohammad Abouchama

Reputation: 131

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.

Upvotes: 4

luizbag
luizbag

Reputation: 152

You need to make a query using user as filter.

On your BlogList class:

class BlogList(generics.ListAPIView):
    queryset = models.Blog.objects.filter(user_id = self.request.user.id)
    serializer_class = serializers.BlogSerializer

Check this link for reference: https://www.django-rest-framework.org/api-guide/filtering/#filtering-against-the-current-user

Upvotes: -2

Related Questions