4
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?

3 Answers 3

5

It seems it is not possible to use aggregation on slicing as this open ticket suggest: https://code.djangoproject.com/ticket/12886

One solution is to execute two distinct queries. The first one to retrieve the sub set of Cars and the second one to actually perform the aggregation:

qs = Car.objects.all()[:3]
sub_sum = Car.objects.filter(pk__in=qs).aggregate(Sum("price"))
3

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).
1
  • looks like django now supports aggregate after slicing. Can someone confirm?
    – Murali K
    Jun 17, 2022 at 9:55
0

As of Django 1.7 (back in 2014) you can aggregate a slice.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.