The docs show a way to embrace the data integrity constraints PostgreSQL provides, f.e. the ExclusionConstraint
for overlapping Ranges.
You can read the suggested solution from the docs here.
I want to have a reservation system which makes sure that a "thing" (here a trainer/teacher) can't be booked twice for a overlapping period of time. I am going with the 2nd example from the documentation where the overlapping criteria is derived from existing fields:
from django.contrib.postgres.constraints import ExclusionConstraint
from django.contrib.postgres.fields import (
DateTimeRangeField,
RangeBoundary,
RangeOperators,
)
from django.db import models
from django.db.models import Func, Q
class TsTzRange(Func):
function = 'TSTZRANGE'
output_field = DateTimeRangeField()
class Reservation(models.Model):
trainer = models.ForeignKey('Trainer', on_delete=models.CASCADE)
start = models.DateTimeField()
end = models.DateTimeField()
cancelled = models.BooleanField(default=False)
class Meta:
constraints = [
ExclusionConstraint(
name='exclude_overlapping_reservations',
expressions=(
(TsTzRange('start', 'end', RangeBoundary()), RangeOperators.OVERLAPS),
('trainer', RangeOperators.EQUAL),
),
condition=Q(cancelled=False),
),
]
So, this works just fine for me and when trying to save an invalid Range, I'll get the expected IntegrityError:
IntegrityError at /admin/trainer/trainingevent/add/
conflicting key value violates exclusion constraint "exclude_overlapping_reservations"
DETAIL: Key (tstzrange(start, "end", '[)'::text), trainer_id)=(["2020-12-19 16:20:00+00","2020-12-19 16:55:00+00"), 1) conflicts with existing key (tstzrange(start, "end", '[)'::text), trainer_id)=(["2020-12-19 16:15:00+00","2020-12-19 16:45:00+00"), 1).
Which leads to my question:
How can I validate the fields or rather make a proper clean()
method to validate the input without duplicating functionality?
From my current perspective the best would be to ask PostgreSQL somehow to check things - or save the Model inside a try catch block somehow.
So, in a more general context the question should be equal to "How to clean an IntegrityError in Django".
Sadly I can't find anything in the docs about this nor anywhere else, so any hints appreciated and thx in advance.