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

Posted

技术标签:

【中文标题】使用Django ORM查询如何注释是不是存在多级外键层次结构【英文标题】:Using Django ORM query How to annotate if multiple levels of foreign key hierarchy exists使用Django ORM查询如何注释是否存在多级外键层次结构 【发布时间】:2016-11-11 01:43:22 【问题描述】:

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

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

【问题讨论】:

这类事情是通过递归来解决的,例如,您创建一个 get_children 方法,该方法遍历每个孩子并调用他们的 get_children 直到没有更多可调用。 【参考方案1】:

尝试使用distinct:

Count('child', distinct=True)

更多详情链接:

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

【讨论】:

以上是关于使用Django ORM查询如何注释是不是存在多级外键层次结构的主要内容,如果未能解决你的问题,请参考以下文章