'Python Django filter avoid overlapping between range dates

I'm having a bit of a logic blank this morning.

I get 2 datetime objects from a user (a range), start_time and end_time.

Idea is to return an exists if there's an overlap between the input range and an existing schedule time.

I tried the following, but I'm far off with the logic.

if Schedule.objects.filter(start_date__gte=ts_start, end_date__lte=ts_start).filter(start_date__gte=ts_end, end_date__lte=ts_end ).exists():


Solution 1:[1]

You almost had it. To find all datetime ranges that overlap you just need to filter where data lower bound is less than the search upper bound and the data upper bound is greater than the search lower bound

overlap = Schedule.objects.filter(
    start_date__lte=ts_end,
    end_date__gte=ts_start
)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Iain Shelvington