在Django中计算和附加过滤的相关对象

时间:2011-03-29 11:05:56

标签: django foreign-keys

我正在尝试计算与另一个对象具有外键关系的对象数,以及删除了标志= 0的对象。

User在模型中与Accounts有外键关系:

class Account(models.Model):
    ...
    def __unicode__(self):
        return self.organisation

class User(models.Model):
    ...
    account = models.ForeignKey("Account", null=True, blank=True)
    deleted = models.BooleanField(blank=False)

views中,对于每个帐户,我想显示附加到帐户的用户数量,这些用户也已删除= 0.

这是我能做的最好的事情:

@login_required
def accounts(request):
    try:
        accounts = Account.objects.all().filter(deleted=0)
        users = User.objects.all().filter(deleted=0)
    except:
        raise Http404

    account_users = {'a':'a'}
    for account in accounts:
        account_users[account.id] = User.objects.all().filter(deleted=0).filter(account = account.id)

    variables = RequestContext(request, {
    'accounts':accounts,
    'users':users,
    'account_users':account_users,
    })
    return render_to_response('accounts/accounts.html', variables)

在上面,我使用的词典包含account.id => non-deleted user count。这个问题是我无法迭代模板中的字典键...

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

使用items()方法迭代字典。它返回(键,值)对上的迭代器。

for k, v in dictionary.items():
   do_something_with(k,v)