简体   繁体   English

Django模型中的order_by vs.aggregate

[英]order_by vs. aggregate in django models

Let's say I have a model called Orders, that has a field 'date' as a DateField with index_db=True. 假设我有一个名为Orders的模型,该模型具有一个字段“ date”作为带有index_db = True的DateField。

given a date, I want to find the closest record in Orders to that date. 给定日期,我想在Orders中找到最接近该日期的记录。

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.. 显然是更快的方法,在后一种情况下,您对ORMing进行两次并计算超出您所需的数量。

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. first()吞下产生的异常,如果queryset不返回任何对象,则返回None。 In case you are trying to get element by index [0] from empty queryset, Python should raise an error. 如果您试图从空查询集中获取索引为[0]元素,则Python应该引发错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM