从日期开始,选择日期时间小于x小时的所有对象

时间:2013-07-01 11:30:56

标签: django django-models

我尝试从单个模型中选择所有对象,其日期时间字段设置从现在开始不到12小时。

我的观看代码:

now = datetime.datetime.now()

# selects all events with date_time field set in future, and with reminder field active
events = Event.objects.filter(reminder=True, reminder_sent=False, date_time__gt=now)

# sets timedelta, as we want to filter previously selected objects to be max 12 hours in future from now
delta = now + datetime.timedelta(hours=12)

# returns nothing, even if in database there are Event objects with date_time field set to 1 hour from now 
expiring_events = events.filter(date_time__lt=delta)

1 个答案:

答案 0 :(得分:4)

now = datetime.datetime.now()
delta = now + datetime.timedelta(hours=12)
events = Event.objects.filter(reminder=True, reminder_sent=False, date_time__range=(now, delta))