简体   繁体   中英

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) :

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. It'll usually return 1 in that case (might depend on your db what value is returned), since there's always 1 value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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