Skip to content Skip to sidebar Skip to footer

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

Solution 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.

Post a Comment for "Django Orm: How Count In Annotation Differ From Count On Query Set?"