1

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               
    Parent.objects.annotate(childs=Count('Child')).values('childs')

-> To Get Number of Grand Childs for parent following query does               
    Parent.objects.annotate(childs=Count('child')).annotate(grandchilds=Count('child__grandchild'))

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

user2959723
  • 651
  • 2
  • 7
  • 13
  • These kinds of things are solved with recursion, for example you make a get_children method that iterates over each child and calls their get_children until there are no more to call. – Lauri Elias Jul 08 '16 at 14:48

1 Answers1

1

Try to use distinct:

Count('child', distinct=True)

More details by link:

https://docs.djangoproject.com/en/1.9/topics/db/aggregation/#combining-multiple-aggregations

Sergei Zherevchuk
  • 562
  • 1
  • 5
  • 14