使用 Django ORM 查询如何注释是否存在多级外键层次结构

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

我的 Django 模型看起来像

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'))

但是我怎样才能得到每个孩子的数量和孙子的数量 parent

尝试使用distinct:

Count('child', distinct=True)

更多详情来自 link:

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