How can I query objects created before a specific hour of the day in Django?
In Django, I'm trying to filter my request only for objects that were created before a specific hour of the day. I have a datetime field named "created_at" that held the datetime from which this object was created.
What I would like to do:
query = query.filter(created_at__hour__lte=10)
Which I would expect to receive all objects that were created before 10am. However, when I try to do this, I get:
FieldError: Join on field 'created_at' not permitted. Did you misspell 'hour' for the lookup type?
I could loop through every day and get the objects of that day, but that seems extremely inefficient. Is there a way to do this in a single request? If not, what's the fastest way to run such a filter?
source to share
__hour
c DateTimeField
is a search type, so you cannot mix it with another search type, for example __lte
. You can create a filter with objects Q
, 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 would be more convenient to keep the creation time TimeField
as well as the existing one created_at
.
source to share