Reputation: 141
I am working on a project and noticed that the Django Sum()
annotation is not working properly when you use it to make a sum of a field with a foreign key.
For example when you have visits to a website on which someone can place an order. The Order
model has a link to the Visit
model because you can place multiple orders in one visit. However, orders that are not coming from the website don't have a website visit. For these orders, the visit will be NULL
. When I do the following, the calculation is not correct (the value is far too high).
visits = visits.annotate(order_total = Sum('order__total'))
When I change Sum
to Avg
, the calculation is done correctly. Is there a logical explanation for this?
Upvotes: 1
Views: 286
Reputation: 141
Solved it using
from pg_utils import DistinctSum
visits = visits.annotate(order_total = DistinctSum('order__total'))
Turns out the Sum
couldn't handle distinct values.
Upvotes: 1