Django:如何迭代模板中的线程注释?

时间:2015-05-17 05:29:31

标签: python django

我创建了一个基本的BranchComment模型(即:一个线程评论系统),它有两个可能的外键属性。一个外键属性是PageInfo模型,如果它是对某人页面的父评论(即:一个新帖子),另一个外键属性,如果评论是对另一个评论的回复,在这种情况下第二个外键设置为一个实际的BranchComment对象,指示它是一个回复的注释。这样,评论可以无限链接到彼此和/或用作页面上的基本新帖子。

这是模特:

class BranchComment(models.Model):
    childtag = models.ForeignKey('self', related_name='child', null=True, blank=True)
    commentcontent = models.CharField(max_length=5000)
    parenttag = models.ForeignKey('PageInfo', related_name='parent', null=True, blank=True)
    commentdate = models.DateTimeField(auto_now_add=True)
    usercommenttag = models.ForeignKey(User, null=True, blank=True) #who posted the comment

     def __unicode__(self):
        return self.commentcontent

显然,您可以使用基本信息获取页面上的所有新帖子:

newposts = BranchComment.objects.filter(parenttag=PageInfo_instance)

然后我可以遍历查询集中的每个父命令并获得相关的回复:

for post in newposts:
    replies = BranchComment.objects.filter(childtag=post).order_by('-commentdate')

所以现在我的问题是我有一个很好的查询集所有的父评论(即:原始帖子)和一个很好的查询集的每个帖子的有序回复,但我如何在模板文件中相互匹配?谢谢你的建议。

1 个答案:

答案 0 :(得分:2)

for post in newposts:
    replies = BranchComment.objects.filter(childtag=post).order_by('-commentdate')

replies将成为BranchComment childtag=post post个<{1>} {/ 1>} newposts的{​​{1}}。

一些想法:

replies = BranchComment.objects.filter(id__in=newposts).order_by('-commentdate')

在模板中,您可以访问相关对象,例如reply.childtagnewpost的所有子项,如下所示:newpost.child。例如,比较它们:

{% if newpost == reply.childtag %}...{% endif %}

请问您能提供更多详情吗?谢谢!