Django:datetime按日期忽略时间过滤 [英] Django: datetime filter by date ignoring time

查看:139
本文介绍了Django:datetime按日期忽略时间过滤的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试过滤某天计划的匹配。我不能只是这样做:

I am trying to filter Matches scheduled in a certain day. I can't just do this:

match_queryset.filter(start=date)

因为它也会按时间过滤,但是我可以这样做:

because it also filters by time, but I can do this:

match_queryset.filter(start__year=a_date.year, start__month=a_date.month, start__day=a_date.day)

但这太复杂了,我觉得可能有一种更简单的方法。

But this is too complex, I feel like there could be a simpler way.

然后我也可以使用范围:

Then I can also use a range:

t0 = datetime.datetime.combine(a_date, datetime.time(0, 0))
t1 = datetime.datetime.combine(a_date, datetime.time(23, 59, 59))
match_queryset.filter(start__gte=t0, start__lte=t1)

但这似乎是一个过大的选择,它可能会生成效率低下的查询。

But this just seems to be an overkill and it probably generates an inefficient query.

我不能只针对某个查询进行查询吗?实际日期?像这样的东西:

Can't I just make a query to target the actual date? Something like:

# this of course doesn't work
match_queryset.filter(start__date=date)

不用说我已经尝试寻找解决方案,但是找不到任何东西。

No need to say I have tried looking for solution and could not find any.

推荐答案

在Django 1.9中,您可以使用 __ date 字段查找,与您在问题中提到的完全相同。对于较旧的版本,您将不得不使用其他方法。

From Django 1.9 you can use the __date field lookup, exactly as you have mentioned in your question. For older versions, you will have to do with the other methods.

例如

Entry.objects.filter(start__date=datetime.date(2005, 1, 1))
Entry.objects.filter(start__date__gt=datetime.date(2005, 1, 1))

这篇关于Django:datetime按日期忽略时间过滤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆