问题
These are my models:
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',
)
and this is my query:
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))
)
For example, i have an entry in Purchase
amount: 2, entry_for: jhon,
amount: 3, entry_for: smith
amount: 5, entry_for: jhon,
amount: 1, entry_for: jhon,
and consume
entry:
amount: 1, entry_for: jhon,
amount: 2, entry_for: smith,
According to above data, my query Sum should return total_consume
for jhon is 1
, but it is returning 3
for jhon in total_consume and smith total_consume is 2
, here smith result is expected but jhon result is unexpected.
I guess, the problem/ wrong calculation occurring because of jhon has 3
entry in the Purchase table, so it is multpliying with total entry of person's purchase and total consume amount, i am not sure why.
Can anyone please help me how can i get the correct calculated result?
I want, it should return,
jhon's total_purchase: 8, total_consume: 1,
smith's total_purchase: 3, total_consume: 2
can anyone help me in case?
回答1:
Django uses joins tables instead of subqueries when there are multiple aggregations as documented already here
Combining multiple aggregations with annotate() will yield the wrong results because joins are used instead of subqueries
You should write subquery for each aggregation
来源:https://stackoverflow.com/questions/61689646/django-annotate-returning-unexpected-sum-value