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

时间:2016-07-08 13:05:34

标签: 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):
    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'))

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

1 个答案:

答案 0 :(得分:1)

尝试使用distinct

Count('child', distinct=True)

更多详情链接:

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