Let's say I have a model called Orders, that has a field 'date' as a DateField with index_db=True.
given a date, I want to find the closest record in Orders to that date.
I can write:
prev_orders = Orders.objects.filter(date__lte=date).order_by('-date')
last_order = prev_orders[0]
or:
from django.db.models import Max
max_date = Orders.objects.filter(date__lte=date).aggregate(Max('date'))['date__max']
last_order = Orders.objects.get(date=max_date)
Which one is faster? are there any other reasons to prefer one for the other?
Orders.objects.filter(date__lte=date).order_by('-date')[0]
is obviously the faster one, in latter case you ORMing twice and calculating things more than you need..
First one is good enough..
prev_orders = Orders.objects.filter(date__lte=date).order_by('-date').first()
first()
swallow the resulting exception and return None if the queryset returns no objects. In case you are trying to get element by index [0]
from empty queryset, Python should raise an error.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.