如何列出特定用户的博客文章。
使用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()),
您需要使用用户作为过滤器进行查询。
在您的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
哪个用户?当前用户?还是其他任何用户?
如果有当前或其他用户,则可以执行此操作:
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提供的页面来学到更多。