Ronald Langeveld
Ronald Langeveld

Reputation: 744

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():

Upvotes: 3

Views: 1000

Answers (2)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476699

Two ranges [b1, e1] and [b2, be] do not overlap if b1>e2, or e1<b2. We can negate this expression to know when two intervals overlap: b1≤e2, and e1≥b2.

This thus means that we can filter with:

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

Upvotes: 3

Iain Shelvington
Iain Shelvington

Reputation: 32244

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
)

Upvotes: 2

Related Questions