How can I filter a date of a DateTimeField in Django?
To filter by date in Django, append __date
to your DateTimeField
in the .filter()
method. Considering Event
as a model with a event_date
field, to get events on the 14th of March, 2023:
This yields all Event
objects whose event_date
falls on March 14, 2023.
Demystifying date-based filtering
Let's unravel the secrets behind date-based filtering in Django and tap into ORM capabilities.
Range-based date filtering
To get Event
objects within a time window, make use of __gte
(greater than or equal to) and __lt
(less than):
This retrieves events beginning on the 14th and ending before the 15th of March, 2023. The use of datetime.combine
with datetime.min.time()
includes all conceivable times during the day.
Year, month, or day-based filtering
Filtering by a specific year, month, or day is conveniently done with __year
, __month
and __day
lookups:
Time zone aware filtering
Time zones could impact your filtering. When filtering by date, datetime.now()
over datetime.utcnow()
or timezone.now()
could give irrelevant results if time zone support is enabled in your Django settings.
Filtering events happening today
To filter the events running today, use date.today()
:
startswith and contains for date filtering
The __startswith
and __contains
lookups could provide quick filtering options that process the date as a string. But, beware, they may not give the calendar structure the reverence it deserves:
Using Django's date-based views
Django ships with some useful built-in views like django.views.generic.date_based
, which helps to normalize the displaying of events happening today, this year, or any other custom relative date context.
Was this article helpful?