Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filtering only on Annotations in Django

Tags:

Taking the example from: http://docs.djangoproject.com/en/dev/topics/db/aggregation/#filter-and-exclude

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

Is there anyway to have the filter only apply to the annotation, so it would return all publishers, with some having a num_books=0?

like image 921
Collin Anderson Avatar asked Jan 19 '10 19:01

Collin Anderson


2 Answers

You can use the annotation variable in the filter.

publishers=Publisher.objects.annotate(num_books=Count('book')).filter(num_books__gte=2) 
like image 156
czarchaic Avatar answered Oct 21 '22 08:10

czarchaic


Hm, I think you have to use an extra clause:

Publisher.objects.extra(select={     'num_books': 'SELECT COUNT(*) ' + \                  'FROM <your_app>_book ' + \                  'WHERE <your_app>_book.publisher_id = ' + \                        '<your_app>_publisher.id AND ' + \                        'rating > 3.0' }) 
like image 28
Maccesch Avatar answered Oct 21 '22 08:10

Maccesch