如何使Django Rest API成为嵌套注释?

时间:2018-10-05 16:33:39

标签: django django-rest-framework django-views django-rest-viewsets

我想为一个android应用程序创建一个嵌套的注释模型,并且我正在使用Django Rest框架。我定义了两个模型PostComment如下:

class Post(models.Model):
    title = models.CharField(max_length=100)
    description = models.TextField()
    author = models.ForeignKey('CustomUser',on_delete=models.CASCADE, related_name="author")
    created_at = models.DateTimeField(auto_now=True, editable=False)
    tag = models.ForeignKey('Tag', on_delete=models.CASCADE, blank=True, null=True)

class Comment(models.Model):
    p_post = models.ForeignKey('Post', on_delete=models.CASCADE)
    description = models.TextField()
    author = models.ForeignKey('CustomUser', on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now=True, editable=False)
    p_comment_id = models.ForeignKey('self', blank=True)
    is_anon = models.BooleanField(default=False)

我遇到的问题是,如果我想获取应用程序上的评论列表,那么我应该如何处理呢?我的脑海中有以下几点:

  1. 我无法返回完整的评论列表,因为这将是很长的列表
  2. 因此,我如何选择限制返回前5条评论以及前5条子评论。

1 个答案:

答案 0 :(得分:0)

如果您将相关名称添加到p_post:

p_post = models.ForeignKey('Post', on_delete=models.CASCADE, related_name="comments")

您将能够像这样遍历它们:

for post in Post.objects.order_by('created_at').all()[0:5]:
    for comment in post.comments.order_by('created_at').all()[0:5]:
        print(comment.description) # do whatever you want with comment

注意:[0:5]用于限制前5名

您还需要在查询帖子时预提取评论:Post.objects.prefetch_related('comments')

编辑:

再次阅读您的问题,我发现这是针对API响应的。我会调查rest_framework.serializers.ModelSerializer

class CommentSerialzier(serializers.ModelSerializer):
    class Meta:
        model = Comment

class PostSerializer(serializers.ModelSerializer):
    comments = CommentSerializer(many=True)
    class Meta:
        model = Post