Why use aggregate to find average value instead of using tutal_sum/n in django

Viewed 304

Here we calculate using aggregate

>>> avg = Book.objects.aggregate(average_price=Avg('price'))
{'average_price': 34.35}

But why we don’t use below concept in above.

a = Books.objects.all()
Avg = sum([x.price for x in a])/len(a)
34.35

I want to know use aggregate rather than second procees.

2 Answers

Book.objects.aggregate(average_price=Avg('price')) - This is converted to a equivalent SQL query and executes on the DB and directly fetches the aggregate data. This is faster.

Whereas using second method

  • you get all objects from DB,
  • calculate sum of prices using sum() and then
  • find the length of a using len() and then
  • use division to get your results.

Second method has more overhead than the first as there are function calls involved, performing division, loading objects to a list etc.,

The first item will calculate the average at the database side. This thus means that you perform a query that determines the average. This is normally faster because databases are designed to calculate this and more important: it will reduce the bandwidth between the database and the Django/Python layer, since the database will only return one row: a row that contains the average_price.

In your second codefragme, you will retrieve all items from the database and deserialize these with Django. This thus means that if there are thousand records, it will take some time to load all the items. Then it turns out we are only interested in the price and the length of the items in the queryset.

If the number of records is really high, for example 100'0000, it is even possible that your Python webserver will run out of memory.

Related