2009-06-05 54 views
2

我正在显示搜索结果的数量,但是,我做了多个搜索。 所以要显示我必须添加它们的结果数量。 所以我已经试过这样:Django:添加结果数量

<p>Found {{ products|length + categories|length + companies|length }} results.</p> 

,但我得到一个错误。 我该怎么做?

回答

3

当你创建你的语境词典,我会做这在您的视图:

'result_count': len(products) + len(categories) + len(companies) 

然后,在你的模板,只需使用:

<p>Found {{ result_count }} results.</p> 
4

Django模板不支持算术运算符。但是,您可以使用add筛选器。我想你需要的东西是这样的:

<p>Found {{ products|length|add:categories|length|add:companies|length }} results.</p> 

另外,您应该计算总的观点,并通过其预先计算的模板。

编辑:继的意见,这个版本应该工作:

{% with categories|length as catlen %} 
{% with companies|length as complen %} 
<p>Found {{ products|length|add:catlen|add:complen }} results.</p> 
{% endwith %} 
{% endwith %} 

然而,这种感觉非常哈克,这将是最好来计算视图的身影。

+0

当我尝试`blah | length | add:blarg | length`我得到TemplateSyntaxError“in t()arg必须是一个字符串或数字“。 – krubo 2009-06-05 09:53:56

+0

你的建议是带来一个错误: int()参数必须是一个字符串或数字,而不是'QuerySet' – R0b0tn1k 2009-06-05 10:29:38

3

我想指出的是范盖尔的答案不是最佳的。 从​​,你应该使用query.count()而不是LEN(查询)

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

所以答案应该是: 在视图:

'result_count': products.count() + categories.count() + companies.count()

的模板保持不变