[Answered ]-Summing columns in Django with related fields

1πŸ‘

βœ…

In order to aggregate, you use a Sum object [Django-doc], not the Python builtin sum.

You can obtain the sum of a single object with:

from django.db.models import Sum

return self.fillups.aggregate(total=Sum('trip_distance'))['total']

If you have to do this for multiple records, it is better to .annotate(…) [Django-doc]:

from django.db.models import Sum

Car.objects.annotate(
    total_distance=Sum('fillups__trip_distance')
)

The Car objects that arise from this queryset will have an extra attribute .total_distance with the sum of the related Fillup trip_distances.

Leave a comment