Django在一个查询中计算父级的所有子模型

2024-09-30 22:25:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着从我的父模型数数所有的孩子,但我不能使它工作。在

请看下面我的模型和我尝试过的东西。在

型号

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')

代码

^{pr2}$

Tags: name模型addfalsetrueautomodelmodels
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”,可以:

^{pr2}$

您正在为每个筛选值创建属性。要获取查询集中特定项的子项计数,必须引用该注释。在

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

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

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

^{pr2}$

相关问题 更多 >