【发布时间】:2018-12-02 02:29:44
【问题描述】:
我在玩 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 对我来说还是个 bug。
为什么下面的查询不是不同/唯一的意图是什么?
User.objects.filter(groups__in=Group.objects.all())
【问题讨论】:
标签: django django-orm