tags:

views:

644

answers:

2

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?

+1  A: 

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.

msanders
When I try `blah|length|add:blarg|length` I get TemplateSyntaxError "int() arg must be a string or a number".
Your suggestion is bringing up an error:int() argument must be a string or a number, not 'QuerySet'
I have made it work (see edited answer), but you'd be better off calculating it in the view.
msanders
+3  A: 

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>
Van Gale
That works great, thanks!