我的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'))
但我怎样才能得到每个父母的孩子数量和大孩子的数量
答案 0 :(得分:1)
尝试使用distinct
:
Count('child', distinct=True)
更多详情链接:
https://docs.djangoproject.com/en/1.9/topics/db/aggregation/#combining-multiple-aggregations