Django没有按日期过滤

时间:2018-06-13 19:09:51

标签: python django

我有一个约会模型如下:

class Appointment(models.Model):
    start_date = models.DateTimeField(null=True)

我有3个条目用于测试目的:

Appointment.objects.all()

返回

<QuerySet [<Appointment: 2018-06-13 14:00:00-04:00>, <Appointment: 2018-06-13 12:00:00-04:00>, <Appointment: 2018-06-14 14:30:00-04:00>]>

今天是:

today = timezone.now()
2018-06-13 18:59:09.884977+00:00

我想明天约会,所以我这样做:

tomorrow = today.date()+datetime.timedelta(days=1)
appointments = Appointment.objects.filter(start_date__date=tomorrow)

appointments = Appointment.objects.filter(start_date__date=datetime.date(tomorrow.year, tomorrow.month, tomorrow.day))

appointments = Appointment.objects.filter(start_date__year=tomorrow.year, start_date__month=tomorrow.month, start_date__day=tomorrow.day)

在任何情况下,它都应该返回一个带有一个条目的Queryset,但返回一个空条。

任何?

2 个答案:

答案 0 :(得分:0)

请尝试仅使用appointments = Appointment.objects.filter(start_date__day=tomorrow.day)

如果这不起作用,也许你在不同的时区有问题:明天val +00:00 ,模特 -04:00

答案 1 :(得分:0)

tomorrow = datetime.date.today() + datetime.timedelta(days=1)
Mymodel.objects.filter(date_time_field__contains=tomorrow)

这帮了我大忙。我找不到最优雅的方式,但是,嘿,它有用