在 Django 中计算和附加过滤的相关对象
我正在尝试计算与另一个对象具有外键关系且标志已删除=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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
要迭代字典,请使用
items()
方法。它返回一个(键,值)对的迭代器。To iterate over dictionary use
items()
method. It returns a iterator over (key, value) pairs.