【问题标题】:Django annotate returning unexpected Sum valueDjango注释返回意外的总和值
【发布时间】:2020-08-24 15:06:42
【问题描述】:

这些是我的模型:

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 for jhon 是 1,但它返回 3 for jhon in total_consume 和 smith total_consume 是 2,这里 smith 结果是预期的,但 jhon 结果出乎意料。

我猜,由于 jhon 导致的问题/错误计算在 Purchase 表中有 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】:

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

    将多个聚合与 annotate() 组合将 yield the wrong results 因为使用连接而不是子查询

    你应该为每个聚合写subquery

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-01-30
      • 2022-08-13
      • 1970-01-01
      • 2020-06-24
      • 2020-01-03
      • 2012-07-02
      • 2014-12-11
      • 1970-01-01
      相关资源
      最近更新 更多