2009-06-05 34 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()

的模板保持不變