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

Python Django:如何迭代模板内的线程注释?,python,django,Python,Django,我创建了一个基本的BranchComment模型(即:一个线程注释系统),它有两个可能的外键属性。如果是某人页面(即:新帖子)上的父评论,则一个外键属性为PageInfo模型;如果评论是对另一个评论的回复,则另一个外键属性为另一个评论。在这种情况下,第二个外键设置为实际的BranchComment对象之一,指示它是对哪个评论的回复。通过这种方式,评论可以无限地相互链接和/或用作页面上的基本新帖子 模型如下: class BranchComment(models.Model): child

我创建了一个基本的
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)
然后,我可以循环查询集中的每个parentcomment并获得相关的回复:

for post in newposts:
    replies = BranchComment.objects.filter(childtag=post).order_by('-commentdate')
所以现在我的问题是,我有一个很好的所有parentcomments的查询集(即:原始帖子)和一个很好的对每个帖子的有序回复的查询集,但是我如何在模板文件中将它们彼此匹配呢?谢谢你的建议

for post in newposts:
    replies = BranchComment.objects.filter(childtag=post).order_by('-commentdate')
回复
将是
BranchComment
对象,其中包含
childtag=post
最后一次
post
newposts

一些想法:

replies = BranchComment.objects.filter(id__in=newposts).order_by('-commentdate')
在模板中,您可以访问相关对象,例如
reply.childtag
newpost
的所有子对象,如下所示:
newpost.child
。例如,比较它们:

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

你能提供更多的细节吗?谢谢

没有任何更多的细节,以提供哈哈,我只是想能够显示所有的评论和答复答复答复等整齐的模板上。BranchComment.objects.filter(id\u in=newposts).order\u by('-commentdate')的具体功能是什么?应该在代码中插入到哪里?我现在明白你的意思了。但是我的回答没有用。您需要类似于
django threadcomments
的东西。我已经看过了,但我想自己编写代码,以便更好地了解发生了什么。