首页 > 解决方案 > Django-ORM:需要不同的。为什么?

问题描述

我在玩 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())

标签: djangodjango-orm

解决方案


原始 MySQL 查询如下所示:

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

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


推荐阅读