简体   繁体   English

Python Django 过滤器避免范围日期之间的重叠

[英]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 .我从用户(一个范围) start_timeend_time得到 2 个datetime时间对象。

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 .如果b 1 >e 2e 1 <b 2 ,则两个范围[b 1 , e 1 ][b 2 , b e ]重叠。 We can negate this expression to know when two intervals overlap: b 1 ≤e 2 , and e 1 ≥b 2 .我们可以否定此表达式以了解两个区间何时重叠: b 1 ≤e 2e 1 ≥b 2

This thus means that we can filter with:因此,这意味着我们可以过滤:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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