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

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

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

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

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

在您的博客列表中 class:

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

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

哪个用户?当前用户?或任何其他用户?

如果有任何用户,当前或其他用户,那么您可以这样做:

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 提供的页面了解更多信息。