【问题标题】:Django count all child models from parent in one queryDjango 在一个查询中计算来自父级的所有子模型
【发布时间】: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)

【问题讨论】:

标签: python django django-models


【解决方案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

【讨论】:

    【解决方案2】:

    你的代码应该是:

    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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-10-29
      • 1970-01-01
      • 2017-02-18
      • 2018-08-15
      • 2020-03-29
      • 1970-01-01
      相关资源
      最近更新 更多