Django Queryset 获取一系列对象而不是 Sum 的结果

Django Queryset getting a sequence of objects instead of result of a Sum

我正在尝试根据特定列值对模型的不同行进行求和,在这种情况下,我想根据一周和特定汽车进行求和,例如:

Car  Week     Payment
1   2020-W06  0
1   2020-W06  0
2   2020-W06  0
1   2020-W05  0

所以我将汽车和周传递给查询,它应该根据这些值获得付款总和

我通过了 Car = 1 和 Week = 2020-W06 并且付款金额 = 800 美元

这是我的查询集:

payed = Pagos.objects.filter(carro_id=1, semana=semana).annotate(total=Sum('pago'))

这是我得到的结果:

<Pagos: Pagos object (6)>, <Pagos: Pagos object (12)>]

我不明白为什么我没有得到总和

models.py

    class Pagos(models.Model):

        carro = models.ForeignKey(
            Carros, on_delete=models.CASCADE, blank=False, null=False)
        pago = models.DecimalField(max_digits=6, decimal_places=2)
        fecha = models.DateField(
            auto_now=False, auto_now_add=False, blank=True, null=True)
        semana = models.CharField(max_length=20)
        startweek = models.DateField(
            auto_now=False, auto_now_add=False, blank=True, null=True)
        endweek = models.DateField(
            auto_now=False, auto_now_add=False, blank=True, null=True)
        renta = models.ForeignKey(
            Renta, on_delete=models.PROTECT, blank=False, null=False)
        created_at = models.DateTimeField(auto_now_add=True)
        updated_at = models.DateTimeField(auto_now=True)

        class Meta:
            verbose_name_plural = "Pagos"

        def get_absolute_url(self):
            return reverse('pagos')


    class Carros(models.Model):

        nombre = models.CharField(max_length=20, blank=True, null=True)
        marca = models.CharField(max_length=25)
        modelo = models.CharField(max_length=25)
        year = models.IntegerField()
        placa = models.CharField(max_length=10, unique=True)
        color = models.CharField(max_length=10)
        conductor = models.ForeignKey(
            Conductores, on_delete=models.SET_NULL, blank=True, null=True)
        propietario = models.ForeignKey(Propietarios, on_delete=models.CASCADE)
        created_at = models.DateTimeField(auto_now_add=True)
        updated_at = models.DateTimeField(auto_now=True)

        class Meta:
            verbose_name_plural = "Vehículos"

        def __str__(self):
            return self.nombre

        def get_absolute_url(self):
            return reverse('carros')

根据 docs annotate 向每个模型对象添加一个文件,这样您就可以获得总和并且可以像这样访问它(docs):

payed[0].total

如果你想获得总值而不是只在一个字段上,你需要使用聚合(docs),它会像:

payed = Pagos.objects.filter(carro_id=1, semana=semana).aggregate(total=Sum('pago'))
print(payed)
# {total: x}

关于您所说的您希望根据可以使用的字段获得不同总和的部分 conditional clauses in your annotate and aggregation