Search code examples
djangodjango-modelsdjango-querysetsubquerygraph-traversal

Django models count children and grand children


In Django models I need help selecting count of children and count of grand children. My models:

Parent:

Child:
 parent = models.Foreignkey(Parent)
GrandChild:
 child = models.Foreignkey(Child)

I did

Parent.objects.annotate(num_child =Count('child’), num_grandchild=Count('child__grandchild'))

With this, I get num_child is exactly same value as num_grandchild

Can you please help


Solution

  • I think you must set distinct on the Count()

    q = Parent.objects.annotate(num_child=Count('child', distinct=True), num_grand_child=Count('child__grandchild', distinct=True))
    

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