python Django Rest如何显示只属于相关博客和作者的评论列表?

5jvtdoz2  于 2022-11-28  发布在  Python
关注(0)|答案(1)|浏览(114)

假设作者Jonone写了一个标题为“作者Jonone写的这个博客”的博客,作者Joe写了一个“作者Joe写的这个博客”的博客。Jonone的博客收到了20条评论,Joe的博客收到了10条评论。当Jonone登录他的帐户时,他只能看到那些属于他的博客文章的评论,Joe也是如此。这里我尝试了这个查询Comment.objects.all().filter(blog__author=request.user.id),但现在每个人仍然可以看到彼此的博客评论从我的api网址。这里是我的代码:

@api_view(['POST', 'GET'])
def comment_api(request): 
    if request.method == 'POST':
        serializer = CommentSerializer(data=request.data)
        if serializer.is_valid():
            serializer.save()
            return Response(serializer.data, status=status.HTTP_201_CREATED)
        return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    if request.method == 'GET':    
        comment = Comment.objects.all().filter(blog__author=request.user.id)
        serializer = CommentSerializer(comment, many=True)
        return Response(serializer.data)

序列化程序.py

class CommentSerializer(serializers.ModelSerializer):
      class Meta:
          model = Comment
          fields = '__all__'

模型.py

class Blog(models.Model):
    author = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True)
    blog_title = models.CharField(max_length=200, unique=True)

class Comment(models.Model):
      name = models.CharField(max_length=100)
      email = models.EmailField(max_length=100)
      comment = models.TextField()
       blog = models.ForeignKey(Blog, on_delete=models.CASCADE)
jvlzgdj9

jvlzgdj91#

我缺少作者ID。将使用Comment.objects.all().filter(blog__author_id=request.user.id)代替此Comment.objects.all().filter(blog__author=request.user.id)

相关问题