In views.py I have this
class CarListView(ListView):
model = Car
def get_context_data(self, **kwargs):
context = super(CarListView, self).get_context_data(**kwargs)
context['max_price'] = Car.objects.all().aggregate(Max('price'))
return context
Aggregate method will be called every time user requests the page. This will add some delay to page loading. I want this max_price variable to be calculated every time admin saved new Car objects. How to do this?
Performance in Django is of very much importance. If you want the requirement to be implemented in ListView go for
Car.objects.all().only('price').aggregate(Max('price'))
The sql query will be
SELECT MAX("table_car"."price") AS "price__max" FROM "table__car"
Here e are not fetching all the table data and so the performance will be much better than fetching all data.
You can use
Car.objects.all().values('price').aggregate(Max('price'))
also.
If you want to get the data when admin saves the data you can do this,
Car.objects.all().values('price').order_by('-price')[0]
This orders the car data based on values and fetches only one entry
SQL query:
SELECT "car"."price" FROM "car" ORDER BY "car__price"."price" DESC LIMIT 1
These will reduce SQL query time and will improve performance.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments