How retrieve all comments of all posts
I have a Blog model, a Post model and a Comment model:
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'))
In a view I retrieve all post with this istruction:
posts = blog.posts.all()
So my question is:
How can I retrieve all comments of all posts in the template ?
I have tryed this but the comments aren't displayed:
{% for post in posts %}
{{ post.title }}
{{ post.body }}
{% for comment in post.comments.all %}
{{ comment.body }}
{% endfor %}
{% endfor %}
You've just missed off the all
.
{% for comment in post.comments.all %}
try with this
{% for comment in post.comments_set.all %}
精彩评论