gpt4 book ai didi

Django-ORM:需要不同的。为什么?

转载 作者:行者123 更新时间:2023-12-02 14:30:35 25 4
gpt4 key购买 nike

我正在使用 django ORM

import django
django.setup()
from django.contrib.auth.models import User, Group
from django.db.models import Count

# All users
print(User.objects.all().count())
# --> 742

# Should be: All users which are in a group.
# But the result is different. I don't understand this.
print(User.objects.filter(groups__in=Group.objects.all()).count())
# --> 1731

# All users which are in a group.
# distinct needed
print(User.objects.filter(groups__in=Group.objects.all()).distinct().count())
# --> 543

# All users which are in a group. Without distinct, annotate seems to do this.
print(User.objects.filter(groups__in=Group.objects.all()).annotate(Count('pk')).count())
# --> 543

# All users which are in no group
print(User.objects.filter(groups__isnull=True).count())
# --> 199

# 199 + 543 = 742 (nice)

我不明白返回 1731 的第二个查询。

我知道我可以使用distinct()。

尽管如此,1731 对我来说看起来像是一个错误。

为什么下面的查询不独特/唯一的意图是什么?

User.objects.filter(groups__in=Group.objects.all())

最佳答案

原始 MySQL 查询如下所示:

SELECT user.id, group.id FROM user LEFT JOIN group ON user.group_id = group.id

结果将包含用户和组的所有可能组合,我猜有些用户属于多个组。

关于Django-ORM:需要不同的。为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50990858/

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