>我有以下模型:User
、UserProfile
和SalesCompany
关系:每个User
都有一个UserProfile
,每个UserProfile
都有一个SalesCompany
。
我需要在SalesCompany
UserProfile
获得所有User
。
有没有比我下面的解决方案更有效的方法?一些注释和遍历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
这应该只执行一个 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及其做事方式感到矛盾甚至有点不喜欢。