Home > Blockchain >  Python Django filter avoid overlapping between range dates
Python Django filter avoid overlapping between range dates

Time:02-28

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

Any suggestions would be much appreciated.

Thanks!

CodePudding user response:

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)

CodePudding user response:

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
)
  • Related