Django:根据外键的开始日期和结束日期进行过滤

Django: Filter based on foreignkey's start date and end date

我有以下两个模型:

class ParentModel(models.model):
    name = models.CharField("Name", max_length = 256, blank = True)    
    start_date = models.DateField(blank = True, null = True)
    end_date = models.DateField(blank = True, null = True)


class ChildModel(models.model):
    name = models.CharField("Name", max_length = 256, blank = True)    
    parent_model = models.ForeignKey(ParentModel, blank = True, null = True, on_delete=models.SET_NULL)
    start_date = models.DateField(blank = True, null = True)
    end_date = models.DateField(blank = True, null = True)

现在我想过滤所有日期范围不在关联父模型日期范围内的子模型。

我试过的代码:

import pandas as pd

child_models = ChildModel.objects.filter(start_date__lte=input_end_date, end_date__gte=input_start_date)
exceeding_child_models = []

for child_model in child_models:
    date_range = pd.date_range(start=child_model.start_date, end=child_model.end_date)
    if child_model.start_date not in date_range or child_model.end_date not in date_range:
        exceeding_child_models.append(child_model)

如何在单个查询中使用 Django ORM 来做到这一点?

两个区间[s1、e1] [s2, e2] 如果 重叠]s1 > e2s2 > e1.

因此我们可以通过以下方式检查:

from django.db.models import <strong>F, Q</strong>

ChildModel.objects.filter(
    Q(start_date__gt=<strong>F(</strong>'parent_model__end_date'<strong>)</strong>) |
    Q(end_date__lt=<strong>F(</strong>'parent_model__start_date'<strong>)</strong>)
)