Filtered annotations without removing results

148 views Asked by At

Consider a model and a query using annotations, for example the following example from the Django documentation: http://docs.djangoproject.com/en/dev/topics/db/aggregation/

Publisher.objects.filter(book__rating__gt=3.0).annotate(num_books=Count('book'))

The result of this query will only contain objects matching the filter (i.e. has a book_rating greater than 3.0), and these objects has been annotated. But what if I want the query to contain all objects, but only annotate objects which matches a filter (or for example annotate them with 0)? Or is this even possible?

1

There are 1 answers

0
Daniel Roseman On BEST ANSWER

No, you can't do that - because that's not how the underlying SQL works.

The only thing I can think of is to do two queries, one with the filter/annotation and one without, then iterate through them in Python, appending the annotation to the matching objects from the non-filtered list.