user2959723 user2959723 - 1 year ago 186
Python Question

Using Django ORM query How to annotate if multiple levels of foreign key hierarchy exists

My Django models looks like

class Parent(models.Model):
name = models.CharField(('name'), max_length=30)

class Child(models.Model):
parent = models.ForeignKey(Parent)
name = models.CharField(('name'), max_length=30)

class GrandChild(models.Model):
child = models.ForeignKey(Child)
name = models.CharField(('name'), max_length=30)

-> To Get Number of Childs for parent following query does

-> To Get Number of Grand Childs for parent following query does

But how can I get the count of number of childs and number of grand childs for each parent

Answer Source

Try to use distinct:

Count('child', distinct=True)

More details by link:

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download