How do I query for objects created before a certain hour in a day in Django?

后端 未结 3 674
鱼传尺愫
鱼传尺愫 2021-01-19 10:56

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

3条回答
  •  Happy的楠姐
    2021-01-19 11:21

    __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.

提交回复
热议问题