Django 注释返回意外的 Sum 值

Django annotate returning unexpected Sum value

这些是我的模型:

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 应该 return total_consume for jhon is 1,但它是 returning 3 for jhon in total_consume 而 smith total_consume 是 2,此处 smith 结果是预期的,但 jhon 结果是意外的。

我想,问题/计算错误是因为 jhon 在购买 table 中有 3 个条目,所以它与个人购买的总条目和总消费金额相乘,我是不知道为什么。

任何人都可以帮助我如何获得正确的计算结果?

我要,应该return,

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

万一有人能帮帮我吗?

当存在多个聚合时,Django 使用连接表而不是子查询,如已记录的那样 here

Combining multiple aggregations with annotate() will yield the wrong results because joins are used instead of subqueries

你应该为每个聚合写 subquery