1

我想为一个 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 条子评论。
4

1 回答 1

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
于 2018-10-05T20:22:57.470 回答