Reputation: 790
Suppose we haw django models Parent
, and Child
. Child
belongs to one Parent
and one Parent
can have multiple children.
class Parent(models.Model):
pass
class Child(models.Model):
parent = models.ForeignKey(Parent)
I would like to obtain set of all parents ordered by the number of children.
Upvotes: 9
Views: 3123
Reputation: 6255
child_set
is the default related_name
of your parent
field in the Child
model. If you've specified a different one, you will have to change the code accordingly.
from django.db.models import Count
ordered_parents = Parent.objects.annotate(num_children=Count('child_set')).order_by('-num_childen')
Hope it helps.
Upvotes: 8
Reputation: 156
read up on aggregate functions in django docs and in any case, you can do parent_instance.child_set.count() to get the number of children and if i'm not mistaken you can filter and also order_by that relation. here's a link for reverse relations
Upvotes: 1