【问题标题】: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 直到没有更多可调用。

标签: python django django-orm django-annotate


【解决方案1】:

尝试使用distinct:

Count('child', distinct=True)

更多详情链接:

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

【讨论】:

    猜你喜欢
    • 2019-10-13
    • 2022-06-27
    • 2019-05-08
    • 1970-01-01
    • 2018-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-14
    相关资源
    最近更新 更多