2013-09-27 5 views
1

객체.필터 나는 다음과 같은 모델을 가지고

UserSalesCompany에 두 개 이상 UserProfile과 함께 입력해야합니다.

내 솔루션보다 효율적인 방법이 있습니까? annotatetraversing 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 

답변

3

이것은 단지 하나의 SQL 쿼리를 실행한다 일을하는 것.

+0

Perfect! 감사합니다. – Gady

+0

다행히도, 장고 코드를 마지막으로 만져 본지 2 년이 지났습니다. 코드 단편을 확인하지 않았습니다. $ –

+0

참 좋은 ... – professorDante

관련 문제