Search code examples
pythondjangoaggregateslicedjango-queryset

Django queryset: aggregate after slicing the queryset doesn't work


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?


Solution

  • aggregate works by modifying the query sent to the DB, causing aggregation to happen on the DB side. You have two choices.

    1. You can use filter to reduce your QuerySet before using aggregate, instead of slicing to reduce it.
    2. You have to do your aggregation in Python, e.g. 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).