简体   繁体   English

Django ORM:注释中的计数与查询集的计数有何不同?

[英]Django ORM: how count in annotation differ from count on query set?

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?为什么这些方法会产生不同的结果?

From the documentation about Count(expression, **kwargs) :从有关Count(expression, **kwargs)文档中:

Returns the number of objects that are related through the provided expression返回通过提供的表达式相关的对象数

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.因此Count专门用于计算相关对象(通过 FK 或 M2M 关系),并且对行本身的任何其他列没有多大意义。 It'll usually return 1 in that case (might depend on your db what value is returned), since there's always 1 value.在这种情况下,它通常会返回 1(可能取决于您的数据库返回什么值),因为总是有 1 个值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM