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

Python 使用Django ORM查询如何注释是否存在多级外键层次结构,python,django,django-orm,django-annotate,Python,Django,Django Orm,Django Annotate,我的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):

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

但是我怎样才能得到每个父母的孩子数和孙子数呢

尝试使用
distinct

Count('child', distinct=True)
更多详情请点击链接:


这类问题可以通过递归来解决,例如,您可以创建一个get\u children方法,该方法迭代每个子级并调用它们的get\u子级,直到没有更多的子级可调用为止。