今天发生的Django筛选器事件

2024-06-01 21:05:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在努力在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

我需要编写一整套不同的选项,还是有一个更简单、更优雅的方法?


Tags: 模型todaydatemodelmodels事件locationstart
3条回答

您需要两个不同的datetime阈值-today_starttoday_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.有一个名为DateTimeField(不是DateField)的foo_date是令人恼火的误导-考虑一下startend…)

我看到的所有答案都不知道时区。

你为什么不这样做呢:

from django.utils import timezone

class EventManager(models.Manager):
    def bookings_today(self, location_id):
        bookings = self.filter(location=location_id, start__gte=timezone.now().replace(hour=0, minute=0, second=0), end__lte=timezone.now().replace(hour=23, minute=59, second=59))

你需要使用这样的范围:

class EventManager(models.Manager):
    def bookings_today(self, location_id):
        from datetime import datetime
        now = datetime.now()
        bookings = self.filter(location=location_id, start__lte=now, end__gte=now)
        return bookings

相关问题 更多 >