In Django, I am trying to filter my query only to objects that were created before a certain hour in the day. I have a datetime field called \'created_at\' that stored the d
__hour
on a DateTimeField
is a lookup type, so you can't mix it with another lookup type like __lte
. You could construct a filter with Q
objects, EG:
before_ten = Q(created_at__hour=0)
for hour in range(1, 11):
before_ten = before_ten | Q(created_at__hour=hour)
query = query.filter(before_ten)
If you can change your data model, it might be more convenient to save a creation time TimeField
as well as your existing created_at
.
import datetime
start_time = datetime.datetime.now().replace(hour=00, minute=00)
certain_hour = 10
end_time = start_time.replace(hour=certain_hour)
query = query.filter(created_at__range=(start_time, end_time)
In Django 1.9+, you can chain hour lookups like created_at__hour__lte
, so the query from the question will work.
query = query.filter(created_at__hour__lte=10)