Django ORM:注释中的计数与查询集上的计数有何不同? [英] Django ORM: how count in annotation differ from count on query set?

查看:54
本文介绍了Django ORM:注释中的计数与查询集上的计数有何不同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

qs = ...

qs = qs.annotate(v=Count('a', filter=Q(a__lt=5)))
a = qs.first().v
b = qs.filter(Q(a__lt=5)).count()

assert a == b  # error

这些方法可能会产生不同的结果吗?

Is there any reason why these methods could produce different results?

推荐答案

来自文档关于 Count(expression,** kwargs)


返回通过提供的表达式关联的对象数

Returns the number of objects that are related through the provided expression

所以 Count 是专门用来计算相关对象(通过FK或M2M关系)的,对行本身的任何其他列都没有多大意义。在这种情况下,通常会返回1(可能取决于您的数据库返回的值),因为总会有1个值。

So Count is specifically meant to count related objects (through FK or M2M relationships), and doesn't make much sense on any other column of the row itself. It'll usually return 1 in that case (might depend on your db what value is returned), since there's always 1 value.

这篇关于Django ORM:注释中的计数与查询集上的计数有何不同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆