gpt4 book ai didi

python - 按两次删除的ForeignKey对象过滤

转载 作者:行者123 更新时间:2023-11-30 23:33:12 25 4
gpt4 key购买 nike

我有以下模型:UserUserProfileSalesCompany

关系:每个用户都有一个UserProfile,每个UserProfile都有一个SalesCompany

我需要获取 SalesCompany 中具有多个 UserProfile 的所有 User

有没有比我的以下解决方案更有效的方法? annotate 的一些组合和 traversing 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

最佳答案

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

关于python - 按两次删除的ForeignKey对象过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19061077/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com