2

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.

1 Answer 1

1

So, I guess it's not possible to reuse the constraint to query for overlapping events, since at the point Django tries to save an object to the database it already has to be cleaned, at least from what I could find out. anyways, I'll leave the constraint active of course because this is a strong guarantee for my data integrity, but to get the functionality I was looking for, I've added a custom manager to the model.

This is as follows, it fits in the "room with reservation" schema (just replace Trainer with Room) but you'll need to modify it to your needs.

from django.db import models


class TrainingEventManager(models.Manager):
    def check_availability(self, trainer, start, end):
        return not (
            super()
            .get_queryset()
            .filter(trainer=trainer)
            .filter(start__gte=start)
            .filter(end__lte=end)
            .exists()
        )

this queries for a given datetime range (start__gte and end__lte), checks if it has entries (exists()) and returns the boolean opposite since I'd like to know the availability not the "is_reserved" answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.