Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
514 views
in Technique[技术] by (71.8m points)

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...