Django中(QuqerySet)Manager::annotate()方法与(Manager)QuerySet::annotate()方法应该使用级联注释aggregate值,而不是joins叉乘

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)

 

>>>

#~~~~~~~~~~

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值