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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With