简体   繁体   English

Django 1.9 日期时间过滤器

[英]Django 1.9 DateTime Filter

I'm attempting to filter a model that contains the field below:我正在尝试过滤包含以下字段的模型:

TEMP_START = models.DateTimeField(null=True)

And I'm using the syntax我正在使用语法

x.filter(TEMP_START__date = datetime.datetime(2016, 3, 31, 8, 0, tzinfo=<UTC>))

However, this returns multiple unique TEMP_START values.但是,这会返回多个唯一的 TEMP_START 值。 I am thinking this is due to my data being stored without time zones.我认为这是由于我的数据没有时区存储。 But, I have set in my settings.py file:但是,我在我的 settings.py 文件中设置了:

TIME_ZONE = 'UTC' # 'America/Chicago'

USE_I18N = True

USE_L10N = True

USE_TZ = True

I am unsure why other unique datetime object values are being returned by this filter statement.我不确定为什么此过滤器语句返回其他唯一的日期时间对象值。 I am aware the "__date" filter is new to Django 1.9.我知道“__date”过滤器是 Django 1.9 的新功能。 Is this just a bug?这只是一个错误吗?

The __date field look-up works on dates (only), as its name suggests. __date字段查找适用于日期(仅),顾名思义。 Not on date-time objects;不在日期时间对象上; time is ignored.时间被忽略。

The documentation , and in particular the example, also show this: 文档,尤其是示例,也显示了这一点:

For datetime fields, casts the value as date.对于日期时间字段,将值转换为日期。 Allows chaining additional field lookups.允许链接额外的字段查找。 Takes a date value.获取日期值。

Example:例子:

Entry.objects.filter(pub_date__date=datetime.date(2005, 1, 1)) Entry.objects.filter(pub_date__date__gt=datetime.date(2005, 1, 1)) Entry.objects.filter(pub_date__date=datetime.date(2005, 1, 1)) Entry.objects.filter(pub_date__date__gt=datetime.date(2005, 1, 1))

As it says: "Takes a date value.".正如它所说:“需要一个日期值。”。 Thus __date is compared to a datetime.date object, not a datetime.datetime object.因此__datedatetime.date对象进行比较,而不是datetime.datetime对象。

Your datetime.datetime object is obviously cast to a datetime.date object under the hood.您的datetime.datetime对象显然被datetime.date为引擎盖下的datetime.date对象。

Using the使用

__contains

keyword seemed to offer the best result and I haven't had issues with it.关键字似乎提供了最好的结果,我没有遇到任何问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM