我有以下模型:User、UserProfile和SalesCompany
关系:每个User人都有一个UserProfile,每个UserProfile人都有一个SalesCompany。
我需要得到一个以上的所有Users at SalesCompanys UserProfile。
有没有比我的以下解决方案更有效的方法?一些注释和遍历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