Reputation: 4306
I'm displaying the number of search results, however, i do more than one search. So to display the number of results i'd have to add them up. So i've tried this:
<p>Found {{ products|length + categories|length + companies|length }} results.</p>
But i get an error. How do i do this?
Upvotes: 3
Views: 7043
Reputation: 97
I'd like to point that Van Gale's answer is not optimal. From the QuerySet API documentation, you should use query.count() rather than len(query)
A count() call performs a SELECT COUNT(*) behind the scenes, so you should always use count() rather than loading all of the record into Python objects and calling len() on the result (unless you need to load the objects into memory anyway, in which case len() will be faster).
So the answer should be: In the view:
'result_count': products.count() + categories.count() + companies.count()
The template remains unchanged
Upvotes: 3
Reputation: 5919
Django templates do not support arithmetic operators. However you can use the add filter. I think you need something like this:
<p>Found {{ products|length|add:categories|length|add:companies|length }} results.</p>
Alternatively you should calculate the total in the view and pass it pre-calculated to the template.
EDIT: Further to the comments, this version should work:
{% with categories|length as catlen %}
{% with companies|length as complen %}
<p>Found {{ products|length|add:catlen|add:complen }} results.</p>
{% endwith %}
{% endwith %}
However, this feels very hacky and it would be preferable to calculate the figure in the view.
Upvotes: 6
Reputation: 43912
I would do this in your view when you are creating your context dictionary:
'result_count': len(products) + len(categories) + len(companies)
Then, in your template, just use:
<p>Found {{ result_count }} results.</p>
Upvotes: 3