我们假设我有modeL;
class MyModel(...):
start = models.DateTimeField()
stop = models.DateTimeField(null=True, blank=True)
我还有两个记录:
- start = 2012-01-01 7:00:00 stop = 2012-01-01 14:00:00
- start = 2012-01-01 7:00:03 stop = 2012-01-01 23:59:59
醇>
现在我想找到第二个查询,所以start datetime应该在start和stop之间,stop应该有23:59:59。如何进行此类查询?
更多信息:
我认为这需要F对象。我想找到所有开始的记录 - >时间是在另一个开始之间 - >时间和停止 - >时间,停止 - >时间是23:59:59,日期与开始时相同
答案 0 :(得分:1)
from django.db.models import Q
q1 = Q( start__range=(start_date_1, end_date_1) )
q1 = Q( start__range=(start_date_2, end_date_2) )
query = (''' EXTRACT(hour from end_date) = %i
and EXTRACT(minute from end_date) = %i
and EXTRACT(second from end_date) = %i''' %
(23, 59,59)
)
MyModel.objects.filter( q1 | q2).extra(where=[query])
注意:在硬答案要求改变之前发布'时间是23:59:59,日期和开始时一样'
答案 1 :(得分:0)
执行查询:“start datetime应该在start和stop之间”
MyModel.objects.filter(start__gte=obj1.start, start__lte=obj1.stop)
但是,我不太了解你的第二个条件。你希望它只与小时23:59:59的对象匹配,但是对于任何一天?
答案 2 :(得分:0)
dt = '2012-01-01 8:00:00'
stop_hour = '23'
stop_minute = '59'
stop_sec = '59'
where = 'HOUR(stop) = %(hour)s AND MINUTE(stop) = %(minute)s AND SECOND(stop) = %(second)s' \
% {'hour': stop_hour, 'minute': stop_minute, 'seconds': stop_ec}
objects = MyModel.objects.filter(start__gte=dt, stop__lte=dt) \
.extra(where=[where])