aldorain
aldorain

Reputation: 790

Django ordering parent model by count of children models in (one to many relation)

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

Answers (2)

Adrián
Adrián

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

Roman Labunsky
Roman Labunsky

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

Related Questions