通过两次删除的ForeignKey对象进行筛选

时间:2013-09-27 22:29:42

标签: python django django-queryset django-orm

我有以下型号:UserUserProfileSalesCompany

关系:每个User都有一个UserProfile,每个UserProfile都有SalesCompany

我需要UserSalesCompanyUserProfile# 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

有没有比以下解决方案更有效的方法? annotatetraversing ForeignKeys的某些组合似乎是解决方案,但我很难过。

{{1}}

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及其做事方式一般都很矛盾甚至不太讨厌。