avg*_*mer 4 django time django-models django-views
我在我的数据库中存储一个对象,其时间字段如下所示:
class MyClass(models.Model):
start_time = models.TimeField(null=True, blank=True)
stop_time = models.TimeField(null=True, blank=True)
Run Code Online (Sandbox Code Playgroud)
这里的想法是,当查询端点时,服务器将只返回当前时间在 start_time 和 stop_time 之间的对象。
注意:start_time 和 stop_time 是一天中的任意时间,可以跨越午夜,但不会超过 24 小时。
我试过了
currentTime = datetime.now().time()
MyClass.objects.filter(stop_time__gte=currentTime, start_time__lte=currentTime)
Run Code Online (Sandbox Code Playgroud)
但这并没有说明时间跨过午夜的时间。
我确信必须有一个简单的解决方案,但网络搜索让我毫无结果。有谁知道这样做的好方法吗?
经过更多的挖掘,我发现这需要两个查询:一个是开始时间小于停止时间(常见情况),一个是大于停止时间(不常见的,午夜后的情况) )。
这是代码:
currentTime = datetime.now().time()
#Returns a list of menus that have start times less than their stop times
list_1 = MyClass.objects.filter(Q(start_time__lte=F('stop_time')), Q(start_time__lte=currentTime), stop_time__gte=currentTime)
#Returns the menus that have start times greater than their stop times (span midnight)
list_2 = MyClass.objects.filter(Q(start_time__gt=F('stop_time')), Q(start_time__lte=currentTime) | Q(stop_time__gte=currentTime))
concat_list = list_1 | list_2
concat_list = concat_list.order_by('-priority')
Run Code Online (Sandbox Code Playgroud)
由于我们使用“|” 为了连接列表,我们可以保留与原始列表相同的特征,例如“order_by()”。仅当连接的数据来自同一模型集时才会出现这种情况。
参考:
| 归档时间: |
|
| 查看次数: |
3393 次 |
| 最近记录: |