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)
我不明白返回 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
结果将包含用户和组的所有可能组合,我猜有些用户属于多个组。
推荐阅读
- c# - 空检查在哪里?
- javascript - 使用 Web Crypto API 的 SubtleCrypto 接口生成确定性密钥对
- python - 是否可以在 python 中使用随机函数?
- python-3.x - 错误:列表索引必须是整数而不是字符串
- python - 用于比较数据框中多列的统计信息的行
- java - 使用 webview Android 下载图像和 mp3
- html - 如何修复在 Edge 上运行良好但在 IE 上无法正常运行的 CSS
- visual-studio-code - 如何使用 VSCode 在 Cygwin shell 中运行自定义任务?
- node.js - Nodemailer Oauth2 错误:未授权客户端
- javascript - 删除脚本后 HTML 页面不会加载