How to filter objects by number of ForeignKey objects WITHOUT using raw SQL?
-
21-04-2021 - |
Question
Is this finally possible in Django? Without this feature, using ORM is kinda strange.
Solution
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)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow