https://docs.djangoproject.com/en/3.1/topics/db/aggregation/
Combining multiple aggregations
Combining multiple aggregations with annotate() will yield the wrong results because joins are used instead of subqueries:
在一个增加注释annotate()中结合多个集合值将产生错误的结果,因为使用了joins而不是子查询级联:
#~~~~~~~~~
>>> book = Book.objects.first()
>>> book.authors.count() #多对多关系字段authors合计一对多关系数目
2
>>> book.store_set.count() #多对多关系字段store_set合计一对多关系数目
3
>>> q = Book.objects.annotate( Count('authors'), Count('store') ) #使用了joins,也就是对每个authors的一对多关系重复统计了store的一对多关系,同时对store的一对多关系重复统计了authors的一对多关系,最终导致Count(‘authors’)与Count(‘store’)的一对多关系计数结果是相乘的结果,也就是都为6个
>>> q[0].authors__count
6
>>> q[0].store__count
6
#~~~~~~~~~
对大多数合计值,没有法子能避免这个joins叉乘的问题,然而,Count()合计有一个distinct参数可以避免joins叉乘:
#~~~~~~~~
>>> q = Book.objects.annotate( Count('authors', distinct=True), Count('store', distinct=True) )
>>> q[0].authors__count
2
>>> q[0].store__count
3
#~~~~~~~~
If in doubt, inspect the SQL query!
In order to understand what happens in your query, consider inspecting the query property of your QuerySet. 如果有疑惑,一定检查SQL查询语句! 为了理解你的查询中发生了什么,考虑检查你的查询集的query属性. #~~~~~~~~~~ >>> qall = Question.objects.all() >>> qall.query <django.db.models.sql.query.Query object at 0x7fd805ab8cd0> >>> help(qall.query)
>>> #~~~~~~~~~~
|