如何在Django REST Api中列出特定用户的博客文章

问题描述 投票:1回答:2

如何列出特定用户的博客文章。

使用ListAPIView,将列出所有博客文章。如何列出特定用户的博客文章?

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()),
python django django-rest-framework django-rest-auth
2个回答
0
投票

您需要使用用户作为过滤器进行查询。

在您的BlogList类上:

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

检查此链接以供参考:https://www.django-rest-framework.org/api-guide/filtering/#filtering-against-the-current-user


0
投票

哪个用户?当前用户?还是其他任何用户?

如果有当前或其他用户,则可以执行此操作:

class BlogList(generics.ListAPIView):
    serializer_class = serializers.BlogSerializer

    def get_queryset(self):
        return Blog.objects.filter(user_id=self.kwargs['user_id'])

并且在urlconf或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()),

因此,这样的URL:'app_name / user_id /'应该为您提供属于具有user_id的用户的所有博客的列表。

此外,您还可以通过访问luizbag提供的页面来学到更多。

© www.soinside.com 2019 - 2024. All rights reserved.