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 %}
Actually, in this very specific case, using the
lengthtemplate filter – which just callslen()– 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 aSELECT COUNT, whereaslen()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
countjust introduces an extra unnecessary database call.So the upshot of all that is that this is better here: