今天发生的 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()

对于给定位置,我想选择今天发生的所有事件。我通过 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

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

原文由 jvc26 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 364
2 个回答

您将需要两个不同的 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_start today_end 所以

 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)

(PS Having a DateTimeField (not a DateField ) called foo_date is irritatingly misleading - consider just start and end …)

原文由 Kristian Glass 发布,翻译遵循 CC BY-SA 3.0 许可协议

我看到的答案都不是时区感知的。

你为什么不这样做:

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

原文由 Anthony Anyanwu 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏