【发布时间】:2019-11-20 16:33:15
【问题描述】:
我正在尝试计算我的父模型中的所有孩子,但我无法让它工作。
以下是我的模型和我尝试过的东西。
型号
class ParentXX(models.Model):
created = models.DateTimeField(auto_now_add=True, null=True)
last_updated = models.DateTimeField(auto_now=True)
name = models.CharField(max_length=200,null=False,blank=False,unique=True)
class ChildrenXX(models.Model):
created = models.DateTimeField(auto_now_add=True, null=True)
last_updated = models.DateTimeField(auto_now=True)
name = models.CharField(max_length=200,null=False,blank=False,unique=True)
parent_sample = models.ForeignKey(ParentXX,
models.CASCADE,
blank=False,
null=False,
related_name='child_sample')
代码
cnt = ParentXX.objects.filter(name="xx").annotate(c_count=Count('child_sample')) #Not working
cnt = ParentXX.objects.filter(name="xx").annotate(c_count=Count('parent_sample')) #Not working
print(c_count)
【问题讨论】:
-
也许这个:
cnt = ParentXX.objects.annotate(number_of_children=Count('children')), This answer here might help!
标签: python django django-models