[Answered ]-Django QuerySet filter by Range with DateTimeField

1👍

That is possible: two ranges can overlap, without that the start time or end time is within the "range" of the other object. For example if the second object is fully contained by the first object.

You can fix this by first determining when two ranges do not overlap. Two ranges [s1, e1] and [s2, e2] do not overlap if s1<e2, or e1<s2. We can negate this expression to know when two intervals overlap: s1≤e2, and e1≥s2.

This thus means that we can check this with:

def clean(self):
    cleaned_data = super().clean()
    start = cleaned_data['start_time']
    end = cleaned_data['end_time']

    queryset = Lesson.objects.exclude(pk=self.instance.pk).filter(
        start_time__lte=end, end_time__gte=start
    )
    if end <= start:
        raise ValidationError('End time cannot be lower than start time!')
    if queryset.exists():
        raise ValidationError('There is an item with overlap!')
    return cleaned_data

Leave a comment