获取Django模型相关集(嵌套)内的对象数

2024-04-28 16:52:58 发布

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

我有三个模型,每一个与另一个有1:n的关系,所以从一个模型我想知道所有子对象的总数

我已经在一个函数中有一个工作代码(如下所示),但我相信它可以在一个查询中完成

class Carton(models.Model):
    id = models.CharField(max_length=15, primary_key=True)
    pallet = models.ForeignKey(Pallet, null=True, blank=True, on_delete=models.SET_NULL)
    # removed the other unrelated fields

class Pallet(models.Model):
    id = models.CharField(max_length=15, primary_key=True)
    group = models.ForeignKey(PalletGroup, on_delete=models.CASCADE)
    # removed the other unrelated fields

class PalletGroup(models.Model):
    id = models.UUIDField(default=uuid.uuid4, primary_key=True)
    # removed the other unrelated fields

    # THIS IS WHAT I THINK COULD BE DONE IN A SINGLE QUERY
    def total_assigned_cartons(self):
        total_assigned_cartons = 0
        for pallet in self.pallet_set.all():
            total_assigned_cartons += pallet.carton_set.count()
        return total_assigned_cartons

我只是想了解它是否可以在单个查询中完成,而不是遍历所有相关对象并计算每个对象的总计数


Tags: the对象keyidtruemodelmodelsclass