faesjeroen
faesjeroen

Reputation: 141

Django Sum Annotation with Foreign key

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 Visitmodel 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 Sumto Avg, the calculation is done correctly. Is there a logical explanation for this?

Upvotes: 1

Views: 286

Answers (1)

faesjeroen
faesjeroen

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

Related Questions