我正在努力在 Django 过滤器中逻辑地表示以下内容。我有一个“事件”模型和一个位置模型,可以表示为:
class Location(models.Model):
name = models.CharField(max_length=255)
class Event(models.Model):
start_date = models.DateTimeField()
end_date = models.DateTimeField()
location = models.ForeignKeyField(Location)
objects = EventManager()
对于给定的位置,我想选择今天发生的所有事件。我已经通过 EventManager 中的“bookings_today”方法尝试了各种策略,但正确的过滤器语法让我望而却步:
class EventManager(models.Manager):
def bookings_today(self, location_id):
bookings = self.filter(location=location_id, start=?, end=?)
date() 失败,因为这会将时间归零,并且一天中的时间对应用程序至关重要,最小和最大日期也是如此,并将它们用作书挡。此外,还有多种可能的有效配置:
start_date < today, end_date during today
start_date during today, end_date during today
start_date during today, end_date after today
我需要编写一整套不同的选项还是有更简单优雅的方法?
最佳答案
您需要两个不同的 datetime
阈值 - today_start
和 today_end
:
from datetime import datetime, timedelta, time
today = datetime.now().date()
tomorrow = today + timedelta(1)
today_start = datetime.combine(today, time())
today_end = datetime.combine(tomorrow, time())
今天发生的任何事情都必须在之前 today_end
并且在之后 today_start
结束,所以:
class EventManager(models.Manager):
def bookings_today(self, location_id):
# Construction of today_end / today_start as above, omitted for brevity
return self.filter(location=location_id, start__lte=today_end, end__gte=today_start)
(P.S. 有一个名为 foo_date
的 DateTimeField
(不是 DateField
)是令人恼火的误导 - 只考虑 start
和结束
...)
关于python - 今天发生的 Django 过滤器事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11245483/