【问题标题】:How to list blog posts of a particular user in Django REST Api如何在 Django REST Api 中列出特定用户的博客文章
【发布时间】:2019-10-17 17:22:58
【问题描述】:

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

使用 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


    【解决方案1】:

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

    如果有任何用户,无论是当前用户还是其他用户,您都可以这样做:

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

    【讨论】:

      【解决方案2】:

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

      在您的 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

      【讨论】:

        猜你喜欢
        • 2016-05-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-09-13
        • 2015-06-03
        • 1970-01-01
        • 2020-11-13
        相关资源
        最近更新 更多