Django annotate返回意外的Sum值

问题描述 投票:0回答:1

这些是我的模型。

class Consume(models.Model):
    amount = models.FloatField(default=1)
    entry_for = models.ForeignKey(
        Person,
        on_delete=models.SET_NULL,
        related_name='consume_entry_for',
    )


class Purchase(models.Model):
    amount = models.DecimalField(
        max_digits=6,
        decimal_places=2,
        default=0.00
    )
    entry_for = models.ForeignKey(
        Person,
        on_delete=models.CASCADE,
        related_name='ledger_entry_for',
    )

这是我的查询。

person_wise_total = Person.objects.annotate(
            total_purchase=Coalesce(Sum('ledger_entry_for__amount'), Value(0)),
            total_consume=Coalesce(Sum('consume_entry_for__amount'), Value(0))
        )

例如,我有一个条目 Purchase

amount: 2, entry_for: jhon,
amount: 3, entry_for: smith
amount: 5, entry_for: jhon,
amount: 1, entry_for: jhon,

consume 的条目。

amount: 1, entry_for: jhon,
amount: 2, entry_for: smith,

根据上面的数据,我的查询Sum应该返回: total_consume 对于江宏来说,就是 1但它正在返回 3 对于jhon在total_consume和smith的total_consume为 2在这里,Smith的结果是意料之中的,而Jhon的结果却是意料之外的。

我想,问题的发生是由于Jhon的计算错误。3 在采购表中的条目,所以它与个人的购买和总消费金额的总条目混合在一起,我不知道为什么。

谁能帮帮我,我如何才能得到正确的计算结果?

我想,它应该返回。

jhon's total_purchase: 8, total_consume: 1,
smith's total_purchase: 3, total_consume: 2

谁能帮助我的情况下?

django django-models django-rest-framework django-orm
1个回答
1
投票

当有多个聚合时,Django使用join表而不是子查询,这一点已经有记录了 此处

将多个聚合与annotate()结合在一起,将使 得不偿失 因为用联接代替了子查询。

你应该写 子查询 对于每一个聚类

© www.soinside.com 2019 - 2024. All rights reserved.