Is this finally possible in Django? Without this feature, using ORM is kinda strange.
Asked
Active
Viewed 101 times
2
-
1Search is a good place to start. I think this has been asked more than once. – S.Lott Feb 02 '12 at 17:00
-
And every answer (that i saw) involve raw SQL. – SuitUp Feb 02 '12 at 17:04
-
naturally after I answered... near duplicate http://stackoverflow.com/questions/1889176/filtering-the-aggregate-in-the-django-orm – istruble Feb 02 '12 at 17:07
2 Answers
2
There are actually two sections in the Django aggregation docs called filtering on annotations and order_by()
that should get you what you need:
books_w_author_count = Book.objects.annotate(num_authors=Count('authors'))
# just a filter by number of objects
books_w_author_count.filter(num_authors__gt=1)
# just ordering on the count
books_w_author_count.order_by('num_authors')
class Author(modules.Model):
# ...
class Book(models.Model):
# ...
authors = models.ManyToManyField(Author)

istruble
- 13,363
- 2
- 47
- 52