Django循环遍历模板中的对象列表

时间:2013-01-10 20:03:46

标签: django list templates object loops

我正在尝试将查询结果存储在列表或类似内容中(尝试不同的替代方案),但我得到的最远的是:

def index(request):
for post in blog_posts:
        comments_total.setdefault(post.id, []).append(comments.total(post.id))
return render_to_response('blog/index.html', {
'comments': comments_total})

在返回数据中我得到: {5L:[2],6L:[1]}

我正在使用此代码访问:

{% if comments %}
{{comments}}<br />
{% for cid in comments %}
{% if cid == post.id %}
{{cid}} - {{comments.cid.0}}<br />
{{cid}} - {{comments.6.0}}
{% endif %}
{% endfor %}
{% endif %}

它打印出来的是:

{5L:[2],6L:[1]} 5 - 5 - 1

是否有替代方法可以获取所有评论,在本例中为博客,计算每篇博文的结果并将其返回给模板?

我要做的是获取博客起始页的计数器。 “你有(X)对这篇文章的评论” - 事情的方式。

1 个答案:

答案 0 :(得分:2)

您可以更有效地“显示每个帖子的评论数量”

假设您有两个模型PostComment。只需在related_name模型中定义ForeignKey帖子Comment关系:

class Comment(models.Model):
    post = models.ForeignKey(Post, related_name='comments')
    # other fields

然后在模板中你可以这样做:

{% for post in posts %}
    {{post.comments.count}}
{% endfor %}
相关问题