Car.objects.all() # 5 cars in db, every car costs 1000 $
Car.objects.all().aggregate(Sum("price")) # result: 5000
# aggregate only on a subset
Car.objects.all()[3:].aggregate(Sum("price")) # result: 5000!, not 3000
# with filter()[3:] i got the same results!
Why? Slicing is not evaluated in db?
How can i achieve that with aggregate?
aggregate
works by modifying the query sent to the DB, causing aggregation to happen on the DB side. You have two choices.
filter
to reduce your QuerySet before using aggregate
, instead of slicing to reduce it. sum(car.price for car in cars)
after slicing. Once you slice, the query is sent to the database, so you can no longer aggregate through the ORM (i.e. QuerySet methods).