Richard Atterfalk
Richard Atterfalk

Reputation: 472

Django loop through a list of objects in template

I'm trying to store the results from a query in a list or similar (trying different alternatives), but the one I have got the furthest with is:

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})

In the return-data I get: {5L: [2], 6L: [1]}

I'm using this code to access:

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

What it prints out in whole is:

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

Is there an alternative for how to get all comments for, in this case, a blog, count through the results for each post and return it to the template?

What I'm trying to do is to get a counter for the start-page of a blog. "You have (X) comments on this post"-kind of thing.

Upvotes: 2

Views: 3078

Answers (1)

Aamir Rind
Aamir Rind

Reputation: 39659

You can do this is in more efficient way "showing counts of comments for each post"

Lets say you have two models Post and Comment. Just define a related_name to the post ForeignKey relationship in Comment model:

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

Then in template you can do:

{% for post in posts %}
    {{post.comments.count}}
{% endfor %}

Upvotes: 2

Related Questions