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.
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)
.
- [Django]-Django/MongoDB tutorials for beginner
- [Django]-Connect to a PostgreSQL database on a Docker container
- [Django]-How to reload Django models without losing my locals in an interactive session?
- [Django]-Django 2.1+ bulk update records with the count of their related records?
- [Django]-Django. How to redirect to url with fragment identifier