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