简体   繁体   中英

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

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
)

Two ranges [b 1 , e 1 ] and [b 2 , b e ] do not overlap if b 1 >e 2 , or e 1 <b 2 . We can negate this expression to know when two intervals overlap: b 1 ≤e 2 , and e 1 ≥b 2 .

This thus means that we can filter with:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM