[Django]-Django: Add number of results

3👍

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>

6👍

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.

3👍

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

Leave a comment