Range query on a datetime is NOT inclusive with dates
|Reported by:||jodym@…||Owned by:||aaugustin|
|Has patch:||no||Needs documentation:||no|
|Needs tests:||no||Patch needs improvement:||no|
I'm using a range test as part of a QuerySet on a DateTimeField. Based on the documentation, I expect this to be inclusive, but if I pass in a datetime.date it is not.
Here's a simple example:
# models: class Transaction(models.Model): posted = models.DateTimeField() # views: start_date = datetime.date(2011, 4, 1) end_date = datetime.date(2011, 4, 30) t = Transaction.objects.filter(posted__range=(start_date, end_date)) # t does NOT contain transactions posted on 2011-04-30, despite range being "inclusive".
Printing t.query reveals:
SELECT "datebug_transaction"."id", "datebug_transaction"."posted" FROM "datebug_transaction" WHERE "datebug_transaction"."posted" BETWEEN 2011-04-01 00:00:00 and 2011-04-30 00:00:00
The conversion to a 00:00:00 datetime.datetime occurs at:
django/db/models/fields/__init__.py(682)to_python() --> 682 if isinstance(value, datetime.date): 683 return datetime.datetime(value.year, value.month, value.day)
The time part needs to be 00:00:00 for the start of the range and 23:59:59.999999 for the end.
Change History (8)
comment:1 follow-up: ↓ 2 Changed 4 years ago by aaugustin
- Component changed from Database layer (models, ORM) to Documentation
- Needs documentation unset
- Needs tests unset
- Patch needs improvement unset
- Triage Stage changed from Unreviewed to Accepted
comment:7 Changed 3 years ago by aaugustin
- Resolution set to invalid
- Status changed from new to closed