【发布时间】:2013-10-04 08:38:21
【问题描述】:
我有以下型号:User、UserProfile 和 SalesCompany
关系:每个User 都有一个UserProfile,每个UserProfile 都有一个SalesCompany。
我需要在SalesCompanys 上获取所有Users 和多个UserProfile。
有没有比我下面的解决方案更有效的方法? annotate 和 traversing ForeignKeys 的组合似乎是解决方案,但我很难过。
# get all users
all_users = User.objects.all().order_by('username')
users = []
# for each user
for user in all_users:
try:
# get profile
profile = UserProfile.objects.get(user=user)
# get count of profiles (i.e. users) at current user's company
count_users = len(UserProfile.objects.filter(company=profile.company))
# if more than one user at company (so not just current user)
if count_users > 1:
# add to users list
users.append(user)
except Exception, e:
pass
【问题讨论】:
标签: python django django-queryset django-orm