Django-ORM:需要与众不同.为什么?

gue*_*tli 5 django 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)
Run Code Online (Sandbox Code Playgroud)

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

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

不过1731对我来说就像一个小虫.

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

User.objects.filter(groups__in=Group.objects.all())
Run Code Online (Sandbox Code Playgroud)

Raz*_*Raz 6

原始MySQL查询如下所示:

SELECT user.id, group.id FROM user LEFT JOIN group ON user.group_id = group.id
Run Code Online (Sandbox Code Playgroud)

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

  • 除此之外,你只是在查询错误的东西.如果你想知道组中有多少用户,`User.objects.exclude(groups__isnull = True).count()`提供了答案.正如Raz所说,您正在查询用户和组的总组合.这是要查询的两个不同的东西. (2认同)

小智 5

您正在尝试从所有组中获取所有用户,但是用户可以在多个组中显示这就是为什么需要使用不同的用户.如果您希望用户在特定组中而不是全部尝试过滤查询.


big*_*ose 3

我假设这User.groups是一种ForeignKey或某种其他关系,将每个关系User与零到多个Group实例相关联。

\n\n

所以这个查询让你感到困惑:

\n\n
User.objects.filter(groups__in=Group.objects.all())\n
Run Code Online (Sandbox Code Playgroud)\n\n

该查询可以描述为:

\n\n
    \n
  • 访问Group模型管理器 ( Group.objects)。
  • \n
  • 制作一个QuerySet:\n\n
      \n
    • 返回所有Group实例 ( Group.objects.all())。
    • \n
  • \n
  • 访问User模型管理器 ( User.objects)。
  • \n
  • 制作一个Queryset:\n\n
      \n
    • Group在外键上加入模型User.groups。
    • \n
    • 返回具有关联的每个 ( User+ ) 行。GroupGroup
    • \n
  • \n
\n\n

这不是 \xe2\x80\x9call 组\xe2\x80\x9d 中的用户;相反,它是\xe2\x80\x9c组存在的所有用户\xe2\x80\x93组对\xe2\x80\x9d。

\n\n

通过对每个多值User.groups字段进行查询,意味着查询必须包含Userto行的联接Group。

\n\n
\n\n

相反,您想要:

\n\n
    \n
  • 访问User模型管理器 ( User.objects)。
  • \n
  • 制作一个QuerySet:\n\n
      \n
    • 返回所有不为空的行groups。
    • \n
  • \n
\n\n
User.objects.filter(groups__isnull=False)\n
Run Code Online (Sandbox Code Playgroud)\n\n

请注意,此 \xe2\x80\x93 \xe2\x80\x9cAll users who has a non-empty set of Associated groups\xe2\x80\x9d \xe2\x80\x93 是您拥有的另一个示例查询的反面(\xe2 \x80\x9c不属于任何组的所有用户\xe2\x80\x9d)。

\n