[Fixed]-Django query sum values from related table

1👍

Here the solution for your problem :

Ticket.objects.all().annotate(
   paid_amount=(F('paid_with_tax') +
        Sum(Coalesce(F('ticketadjustment__value_with_tax'), 0))
    )
).values_list('id', 'paid_amount')

values_list select the field you want in your result.

In your primary request there is a big problem.

Sum(F('paid_with_tax') + Coalesce(F('ticketadjustment__value_with_tax'), 0) * use)

This ligne miltiply value_with_tax with zero. So give you zero. It’s like :

Sum(F('paid_with_tax'))

You want the sum of value_with_tax for each ticket, this is why I move Sum on it :

Sum(Coalesce(F('ticketadjustment__value_with_tax'), 0)) 

And after add the value of paid_with_tax

NB : I remove your variable use, because don’t know is goal.

Leave a comment