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.
- [Django]-Import modules that are above project root
- [Django]-How do you produce/create tables in Geraldo Reports?
- [Django]-Django Create Multiple Objects (Same Model) From One Form
- [Django]-Haystack / Whoosh Index Generation Error
- [Django]-How do I create a user using OAuth2?
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
- [Django]-Can't debug django app in VS Code with docker database: 'could not translate host name "db" to address: Name or service not known'
- [Django]-Social media link in Django
- [Django]-Caching results of a Django function call with cache.get_or_set()
- [Django]-Vue.js in Django Templates