简体   繁体   中英

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. I am thinking this is due to my data being stored without time zones. But, I have set in my settings.py file:

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. Is this just a bug?

The __date field look-up works on dates (only), as its name suggests. 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))

As it says: "Takes a date value.". Thus __date is compared to a datetime.date object, not a datetime.datetime object.

Your datetime.datetime object is obviously cast to a datetime.date object under the hood.

Using the

__contains

keyword seemed to offer the best result and I haven't had issues with it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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