2

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.

2
  • Are you using any particular module for your commenting system? Some of them (like Disqus) have built in functions for returning information like this. Commented Jan 10, 2013 at 20:31
  • No extra modules. The only module I have is the custom I made for comments and posts, which is fairly simple "load it neatly into the database". Commented Jan 10, 2013 at 22:15

1 Answer 1

2

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 %}
Sign up to request clarification or add additional context in comments.

2 Comments

I did try this, but it didn't work out. Gives me an "UnboundLocalError" because "comments" was referenced before assignment. Is the related_name taken from any variable which I might have in the model, or just out of the blue?
Is the error came from model? If yes you might have missed single quotes it should be related_name='comments'. No related_name is not taken from any variable, it just defined directly there as a string

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.