我有以下型号:User
,UserProfile
和SalesCompany
关系:每个User
都有一个UserProfile
,每个UserProfile
都有SalesCompany
。
我需要User
个SalesCompany
以UserProfile
个# 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
。
有没有比以下解决方案更有效的方法? annotate和traversing ForeignKeys
的某些组合似乎是解决方案,但我很难过。
{{1}}
答案 0 :(得分:3)
这应该只执行一个SQL查询:
companies_with_more_than_1_user = (
Company.objects
.annotate(num_users=Count('userprofile'))
.filter(num_users__gt=1)
)
users = User.objects.filter(userprofile__company__in=companies_with_more_than_1_user)
像这样的东西是喜欢Django ORM的理由,尽管我对Django及其做事方式一般都很矛盾甚至不太讨厌。