[Django]-Multiple Django annotate Count over reverse relation of a foreign key with an exclude returns a strange result (18)

3๐Ÿ‘

I found the answer to this issue.

Tl;dr:

You need to add distinct=True inside the Count like this:

AggregatePerson.objects.annotate(counter=Count('author__books', distinct=True))

Longer version:

Adding a Count annotation is adding a LEFT OUTER JOIN behind the scene. Since we add two annotations, both referring to the same table, the number of selected and grouped_by rows is increased since some rows may appear twice (once for the first annotation and another for the second annotation) because LEFT OUTER JOIN allows empty cells (rows) on select from the right table.

๐Ÿ‘คalonisser

1๐Ÿ‘

(repeating essentials of my reply in another forum)

This looks like a Django bug. Possible workarounds:

1) Add the two annotations in one annotate() call:
...annotate(existing_subs=Count('parent__subscriptions'),counter=Count('author__books'))...

2) Replace the annotation for existing_subs and exclude(existing_subs=0) with an exclude (parent__subscriptions=None).

๐Ÿ‘คShai Berger

Leave a comment