简体   繁体   English

获取 model object 的最佳方法,它的 DateTime 字段在 DateTime 中与当前 DateTime 最接近

[英]Best way to get the model object that has a DateTime field closest in DateTime to current DateTime

I want to make an efficient ORM query that returns the model object in which the objects datetime is the closest to the current datetime.我想做一个高效的 ORM 查询,返回 model object 对象日期时间最接近当前日期时间。

So if the current datetime is 22/08/2022 15:00 and I have objects with datetimes of object1.datetime == 22/08/2022 15:30 and object2.datetime == 22/08/2022 15:45 I want to be able to query the DB for the object with the closest datetime which would be the object1 object.因此,如果当前日期时间是22/08/2022 15:00并且我的对象的日期时间为 object1.datetime == object1.datetime == 22/08/2022 15:30object2.datetime == 22/08/2022 15:45我想要能够查询 object 的数据库,其中最接近的日期时间将是object1 object。

So basically I want to find the object that is closest, in the future, to the current datetime.所以基本上我想找到未来最接近当前日期时间的 object。

The only solutions I've been able to think of are inefficient and involve looping and comparing multiple objects by adding them to lists etc.我能想到的唯一解决方案效率低下,并且涉及通过将多个对象添加到列表等来循环和比较多个对象。

dt = datetime.datetime.now()
objs = Model.objects.all()
for obj in objs:
    if obj.dateTime //etc...

Obviously this isn't a good solution because it's going to loop through my whole model database.显然这不是一个好的解决方案,因为它会遍历我的整个 model 数据库。 How can I make this query in the most efficient way?如何以最有效的方式进行此查询?

Try something like:尝试类似:

dt = original_object.dateTime

# get all objects with date later or equal to current
query = Model.objects.filter(dateTime__gte=dt)

# order them by `dateTime`
query = query.order_by("dateTime")

# exclude original object
query = query.exclude(id=original_object.id)

# pick first, since it should be the closest to your original object
closest_object = query.first()

Using objects.filter range datetimes and order the queryset使用 objects.filter 范围日期时间并对查询集进行排序

model.objects.filter(date__gte=d2,date__lte=d1).order_by('date')[0]

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

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