Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 664
aldorain Avatar asked Aug 22 '13 08:08

aldorain


2 Answers

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.

like image 144
Adrián Avatar answered Sep 20 '22 23:09

Adrián


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

like image 29
Roman Labunsky Avatar answered Sep 17 '22 23:09

Roman Labunsky