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?

+3


source to share


3 answers


__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

.

+1


source


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)

      



0


source


In Django 1.9+ you can keep track of time in hours, for example created_at__hour__lte

, so the query from the question will work.

query = query.filter(created_at__hour__lte=10)

      

0


source







All Articles