2011-03-11 65 views
1

我是Django的新手。我想計算並顯示滿足條件的條件的對象的數量。在Django模板中計數對象

我有一個用戶模型和帳戶模型。用戶有一個foreignkey字段帳戶,該帳戶映射到一個Account對象。

在模板中,我想要統計每個帳戶的用戶數量。

我已經得到的最接近的是:

{% for account in accounts %} 

    {% for user in users %} 

     {% if equal user.account.id account.id %} 

      {{ user.count }} 

     {% endif %} 

    {% endfor %} 

{% endfor %} 

感謝

回答

3

從你的模板,好像用戶字段定義是這樣的:

class User(models.Model): 
    . 
    . 
    account=models.Foreignkey() 
    . 

如果是這樣的事情,你可以按照this

{% for account in accounts %} 
    Count: {{ account.user_set.count }} 
    {% for user in account.user_set.all %} 
     {{ user }} 
    {% endfor %} 
{% endfor %} 
+0

沒有工作,但謝謝。我不知道這是否應該在視圖而不是模板中完成,然後作爲上下文傳遞? – eli 2011-03-11 11:35:01

+0

您的用戶帳戶字段是否像我建議的那樣定義? – crodjer 2011-03-11 11:38:03

+0

是的,帳號是用戶的外鍵。我想統計每個帳戶的用戶數 – eli 2011-03-11 11:40:31

3

您可以在視圖中的用戶數註釋您的帳戶。假設用戶模型包含account = ForeignKey(Account, related_name='users')

accounts = Account.objects.annotate(user_count=models.Count('users')) 

這樣你只需要一個查詢。然後只需在您的模板中使用以下內容:

{% for account in accounts %} 
    {{ account.user_count }} 
{% endfor %} 
+0

感謝您的回覆。我試過但得到了一個N​​ameError(全局名稱'模型'未定義。) – eli 2011-03-11 11:59:50

+1

將此添加到您的python文件的頂部:'django.db import models' – 2011-03-11 12:47:28