Search code examples
djangodjango-querysetdjango-ormdjango-filters

Django filter datetime based on month and day only in a range


I am trying to filter model objects in between a certain range. If I consider the year then I am able to do it fine like below:

today = datetime.date.today()
start_date = today + datetime.timedelta(days = 1)
end_date = today + datetime.timedelta(days = 7)

for required_day in required_days:
        filter_dict.update({
                        required_day + "__range" : [start_date, end_date]
                        })

list_of_Q = [Q(**{key: val}) for key, val in filter_dict.items()]

if list_of_Q:
    model_objects = Model.objects.filter(reduce(operator.or_, list_of_Q))

But what I would like to do is to filter only by the values of day and month of the datetime.

I tried as below:

for required_day in required_days:
        filter_dict.update({
                        required_day + "__month__gte" : start_date.month,
                        required_day + "__day__gte" : start_date.day,
                        required_day + "__month__lte" : end_date.month,
                        required_day + "__day__lte" : end_date.day,
                        })

But I am not getting the correct values here. How can I rectify it?


Solution

  • The problem was that in list_of_Q each item in filter_dict was considered separately. So when I used reduce on list_of_Q, it was filtering considering each required_day's start_date and end_date separately.

    So the solution that I wrote is as below:

    filter_list = []
    
    for required_day in required_days:
        filter_list.append(Q(**{
                        required_day + "__month__gte" : start_date.month,
                        required_day + "__day__gte" : start_date.day,
                        required_day + "__month__lte" : end_date.month,
                        required_day + "__day__lte" : end_date.day,
                        }))
    
    if filter_list:
        #continue with the logic
    

    Now this adds Q objects for each required_day as a whole.