Search code examples
djangopython-2.7datefiltermodels

Filter two dates in one query django/python


Is there a way I can filter two datefield columns from a table on the same query?

Example:

I have date_ots and date_lta I need to filter and get the result from today + 4 days on both columns.

Thanks for your attention,

Alex


Solution

  • If you would like exact timing (hours, min, sec), you can do:

    from datetime import timedelta
    
    four_days_from_now = timezone.now() + timedelta(days=4)
    query = Model.objects.filter(date_ots=four_days_from_now, date_lta=four_days_from_now)
    

    If you only want the date 4 days from now (at any time), you can do:

    from datetime import timedelta
    
    four_days_from_now = timezone.now().date() + timedelta(days=4)
    query = Model.objects.filter(date_ots=four_days_from_now, date_lta=four_days_from_now)