查询以检查datetime对象是否未返回预期结果

时间:2015-03-04 21:25:30

标签: python django

我有一个模特

class Availability(models.Model):
    arena = models.ForeignKey(Arena, null=True)
    start_date = models.DateTimeField()
    end_date = models.DateTimeField()

存储特定Arena的可用性对象。在我的观点中,我试图找出Availability objects特定舞台上的所有Today,即从午夜到午夜。为此,我做了以下事情:

def get_schedule(request):
    if 'arena' in request.GET:
        arena = Arena.objects.get(id=request.GET['arena'])
        today = datetime.date.today()
        tomorrow = datetime.date.today() + datetime.timedelta(days=1)
        available_object = Availability.objects.filter(arena__id=arena.id, start_date__gte=today, end_date__lte=tomorrow)
        obj = []
        for a in available_object:
            print(a)
            obj.append({
                'start_time': a.start_date.strftime('%H:%M'),
                'end_time': a.end_date.strftime('%H:%M')
            })
        return HttpResponse(json.dumps(obj), content_type="application/json")

在我的表格中,我创建了以下对象

id = 1
start_date = 2015-03-04 06:00:00
end_date = 2015-03-04 09:00:00
arena_id = 2

在上面的arena_id查询中将available_object传递为2将不返回任何值。我错过了什么?

1 个答案:

答案 0 :(得分:0)

您的天真 today可能是您测试时的2014-03-04 06:00:00之后的日期。尝试在今天和明天使用时区感知日期:

from django.utils import timezone
...
today = timezone.now().replace(hour=0, minute=0, second=0)
tomorrow = today + timedelta(days=1)