views:

25

answers:

2

In my view I return all posts of one blog:

    posts = Post.objects.filter(blog=blog)

and pass it to context.

But.. How can I get the number of posts in the template ?

This is my template:

 <h1>Number of posts: {{ ??? }}  </h1>

 {% for post in posts %}

 {{ post.title }}

 {{ post.body }}

 {% endfor %}
+5  A: 
 <h1>Number of posts: {{ posts.count }}  </h1>

Actually, in this very specific case, using the length template filter - which just calls len() - would be more efficient. That's because calling .count() on a queryset that hasn't been evaluated causes it to go back to the database to do a SELECT COUNT, whereas len() forces the queryset to be evaluated.

Obviously, the former is usually more efficient if you aren't going to evaluate the full queryset then and there. But here, we are immediately going to iterate through the whole queryset, so doing the count just introduces an extra unnecessary database call.

So the upshot of all that is that this is better here:

 <h1>Number of posts: {{ posts|length }}  </h1>
Daniel Roseman
+1 for clearly explaining the difference between .count() and the length filter
Chris Lawlor
+1  A: 

Check out the length filter.

Hank Gay