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_distance
s.
Source:stackexchange.com