【问题标题】:Filter by twice-removed ForeignKey objects按两次删除的 ForeignKey 对象过滤
【发布时间】:2013-10-04 08:38:21
【问题描述】:

我有以下型号:UserUserProfileSalesCompany

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

我需要在SalesCompanys 上获取所有Users 和多个UserProfile

有没有比我下面的解决方案更有效的方法? annotatetraversing 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

【问题讨论】:

    标签: python django django-queryset django-orm


    【解决方案1】:

    这应该只执行一个 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 及其做事方式持矛盾态度甚至有点不喜欢。

    【讨论】:

    • 很高兴它起作用了——自从我上次接触任何 Django 代码以来已经 2 年了,而且我没有验证 sn-p :$
    猜你喜欢
    • 2012-07-23
    • 2017-06-26
    • 2018-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-29
    相关资源
    最近更新 更多