我有Blog模型,Post模型和Comment模型:
class Blog(models.Model):
title = models.CharField(_('name'), max_length=80)
creator = models.ForeignKey(User, related_name="created_pages")
created = models.DateTimeField(_('created'), default=datetime.now)
description = models.TextField(_('description'), null=True, blank=True)
class Post(models.Model):
title = models.CharField(_('title'), max_length=60, blank=True, null=True)
body = models.TextField(_('body'))
blog = models.ForeignKey(Blog, related_name="posts")
user = models.ForeignKey(User)
comments = generic.GenericRelation(Comment)
class Comment(models.Model):
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField(_('object ID'))
content_object = generic.GenericForeignKey()
user = models.ForeignKey(User)
body = models.TextField(_('body'))
在视图中,我使用此结构检索所有帖子:
posts = blog.posts.all()
所以我的问题是:
如何检索模板中所有帖子的所有评论?
我试过了,但没有显示评论:
{% for post in posts %}
{{ post.title }}
{{ post.body }}
{% for comment in post.comments.all %}
{{ comment.body }}
{% endfor %}
{% endfor %}
答案 0 :(得分:2)
你错过了all
。
{% for comment in post.comments.all %}
答案 1 :(得分:1)
试试这个
{% for comment in post.comments_set.all %}