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

发布于 2024-10-27 07:21:52 字数 1132 浏览 2 评论 0原文

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

用户与模型中的帐户有外键关系:

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)

视图中,对于每个帐户,我想显示用户数量哪些人附加到该帐户,哪些人也已删除=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 =>; 未删除用户数量。问题是我无法迭代模板中的字典键...

感谢您的帮助。

I am trying to count the number of objects with have a foreign key relationship to another object, and which have the flag deleted=0.

User's have a foreignkey relationship to Accounts in the models:

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)

In the views, for each account I would like to show the number of users who are attached to the account, which also have deleted=0.

Here's the best I could do:

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

In the above, I'm using a dictionary which contains account.id => non-deleted user count. The problem with this is I can't iterate over the dictionary key in the template...

Thanks for any help.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

孤独难免 2024-11-03 07:21:52

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

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

To iterate over dictionary use items() method. It returns a iterator over (key, value) pairs.

for k, v in dictionary.items():
   do_something_with(k,v)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文