Django filter events occurring today

前端 未结 6 724
伪装坚强ぢ
伪装坚强ぢ 2020-12-09 09:56

I\'m struggling to logically represent the following in a Django filter. I have an \'event\' model, and a location model, which can be represented as:

class          


        
6条回答
  •  死守一世寂寞
    2020-12-09 10:45

    You'll need two distinct datetime thresholds - today_start and 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())
    

    Anything happening today must have started before today_end and ended after today_start, so:

    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. Having a DateTimeField (not a DateField) called foo_date is irritatingly misleading - consider just start and end...)

提交回复
热议问题