1
User
을 SalesCompany
에 두 개 이상 UserProfile
과 함께 입력해야합니다.
내 솔루션보다 효율적인 방법이 있습니까? annotate과 traversing ForeignKeys
의 몇 가지 조합이 해결책 인 것처럼 보이지만 나는 혼란 스럽습니다. 이 장고 ORM을 좋아하는 이유는처럼 일반적으로 양가 심지어는 약간 장고와 그것의 방법으로 싫어 해요에도 불구하고,
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)
재료 :
# 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
Perfect! 감사합니다. – Gady
다행히도, 장고 코드를 마지막으로 만져 본지 2 년이 지났습니다. 코드 단편을 확인하지 않았습니다. $ –
참 좋은 ... – professorDante