How to return number of rows in the template
In my view I return all posts of one 开发者_如何学Cblog:
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 %}
<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>
Check out the length
filter.
精彩评论