Django在一次查询中计算父代的所有子代模型

时间:2019-07-11 02:54:55

标签: python django django-models

我正在尝试计算父模型中的所有孩子,但我无法使其正常工作。

有关我的模型和尝试过的内容,请参见下文。

型号

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)

2 个答案:

答案 0 :(得分:1)

您正在为每个过滤后的值创建一个属性。要获取查询集中特定项目的子代数,您必须引用该批注。

qs = ParentXX.objects.filter(name="xx").annotate(c_count=Count('child_sample')) 

cnt1 = qs[0].c_count
cnt2 = qs[1].c_count
#...

我不确定这是否是最好的方法,但是您可以循环查询集并汇总所有计数。

count = 0
for q in qs:
  count += q.c_count

答案 1 :(得分:0)

您的代码应为:

cnt = ParentXX.objects.filter(name="xx").annotate(c_count=Count('child_sample')) 
cnt = ChildrenXX.objects.filter(name="xx").annotate(c_count=Count('parent_sample')) 

'cnt'是一个QuerySet对象,如果要获取'c_count',则可以:

print(cnt[0].c_count)