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

血红的双手。 提交于 2019-12-25 00:02:31

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/58063167/django-orm-how-count-in-annotation-differ-from-count-on-query-set

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!