Django过滤今天发生的事件

jvc*_*c26 15 python django

我正在努力在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()
Run Code Online (Sandbox Code Playgroud)

对于给定的位置,我想选择今天发生的所有事件.我已经通过EventManager中的'bookings_today'方法尝试了各种策略,但正确的过滤器语法使我不知所措:

class EventManager(models.Manager):
    def bookings_today(self, location_id):
        bookings = self.filter(location=location_id, start=?, end=?)
Run Code Online (Sandbox Code Playgroud)

date()失败,因为这会缩短时间,白天的时间对应用程序至关重要,日期的最小值和最大值也是如此,并将它们用作书挡.此外,还有多种可能的有效配置:

start_date < today, end_date during today
start_date during today, end_date during today
start_date during today, end_date after today
Run Code Online (Sandbox Code Playgroud)

我是否需要编写一整套不同的选项或者是否有更简单优雅的方法?

Kri*_*ass 29

你需要两个不同的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())
Run Code Online (Sandbox Code Playgroud)

今天发生的任何事情都必须在之前 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)
Run Code Online (Sandbox Code Playgroud)

(PS有一个DateTimeField(不是DateField)被称为foo_date是不快误导性-只考虑startend...)


Ant*_*nwu 9

我看到的所有答案都没有时区意识。

你为什么不这样做:

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))
Run Code Online (Sandbox Code Playgroud)


Aid*_*tis 7

你需要像这样使用范围:

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
Run Code Online (Sandbox Code Playgroud)


suh*_*lvs 5

timezone.localtime(timezone.now()).date()为您提供正确的日期。

要获取今天发生的事件start

from django.utils import timezone

class EventManager(models.Manager):
    def bookings_today(self, location_id):
        t = timezone.localtime(timezone.now())
        bookings = self.filter(location=location_id, start__year = t.year,
            start__month = t.month, start__day = t.day, )
Run Code Online (Sandbox Code Playgroud)