【发布时间】: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