[英]Django: How to iterate over threaded comments inside of a template?
I've created a basic BranchComment
model (ie: a threaded comment system) which has two possible foreign key attributes. 我创建了一个基本的
BranchComment
模型(即:线程注释系统),该模型具有两个可能的外键属性。 One foreign key attribute is to the PageInfo
model if it is a parent comment on someone's page (ie: a new post) and another foreign key attribute if the comment is a reply to another comment in which case the second foreign key is set to one of the actual BranchComment objects, indicating which comment it is a reply to. 如果一个外键属性是某人页面上的父注释(即新帖子),则该属性为
PageInfo
模型;如果该注释是对另一条注释的答复,则为另一个外键属性,在这种情况下,第二个外键设置为一个实际BranchComment对象的名称,指示它是对哪个评论的答复。 This way, comments can be infinitely chained to each other and/or used as a basic new post on a page. 这样,评论可以无限地彼此链接和/或用作页面上的基本新帖子。
Here's the model: 这是模型:
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
Obviously, you can get all the new posts on a page using the basic: 显然,您可以使用以下基本方法在页面上获取所有新帖子:
newposts = BranchComment.objects.filter(parenttag=PageInfo_instance)
Then I can loop over each parentcomment in the queryset and get the associated replies: 然后,我可以遍历queryset中的每个父注释并获取相关的答复:
for post in newposts:
replies = BranchComment.objects.filter(childtag=post).order_by('-commentdate')
So now my question is that I have a nice queryset of all the parentcomments (ie: original posts) and a nice queryset of ordered replies to each post, but how do I match them to one another in the template file? 所以现在我的问题是,我对所有父注释(即原始帖子)都有一个很好的查询集,并且对每个帖子都有一个很好的排序回复查询集,但是我如何在模板文件中将它们彼此匹配? Thanks for any advice.
感谢您的任何建议。
for post in newposts:
replies = BranchComment.objects.filter(childtag=post).order_by('-commentdate')
replies
will be BranchComment
objects with childtag=post
of last post
in newposts
. replies
将BranchComment
使用对象childtag=post
最后的post
在newposts
。
Some ideas: 一些想法:
replies = BranchComment.objects.filter(id__in=newposts).order_by('-commentdate')
In templates you can access related objects, for example reply.childtag
or all children of newpost
like this: newpost.child
. 在模板,您可以访问相关的对象,例如
reply.childtag
或所有儿童newpost
这样的: newpost.child
。 And, for example, compare them: 并且,例如,比较它们:
{% if newpost == reply.childtag %}...{% endif %}
Could you provide more details, please? 您能提供更多详细信息吗? Thanks!
谢谢!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.