简体   繁体   中英

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.

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.

So basically I want to find the object that is closest, in the future, to the current datetime.

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. 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

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

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.

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