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

后端 未结 3 653
鱼传尺愫
鱼传尺愫 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条回答
  • 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.

    0 讨论(0)
  • 2021-01-19 11:46
    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 讨论(0)
  • 2021-01-19 11:47

    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)
    
    0 讨论(0)
提交回复
热议问题