【发布时间】: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