Prevent DateRangeField overlap in Django model?

Now that Django supports DateRangeField , is there a way to "Pythonic" to prevent overlapping date ranges?

Hypothetical precedent

One of the hypothetical use cases will be a reservation system in which you do not want people to order the same resource at the same time.

Hypothetical Code Example

class Booking(models.model):
    # The resource to be reserved
    resource = models.ForeignKey('Resource')
    # When to reserve the resource
    date_range = models.DateRangeField()

    class Meta:
        unique_together = ('resource', 'date_range',)
+4
source share
1 answer

full_clean , ModelForm. , . Django, ! , , , save .

class Booking(models.model):

    def full_clean(self, *args, **kwargs):
        super(Booking, self).full_clean(*args, **kwargs)

        o = Booking.objects.filter(date_range__overlap=self.date_range).exclude(pk=self.pk).first()
        if o:
            raise forms.ValidationError('Date Range overlaps with "%s"' % o)

    # do not need to do this if you are only saving the object via a ModelForm, since the ModelForm calls FullClean.
    def save(self):
        self.full_clean()
        super(Booking, self).save()
0

Source: https://habr.com/ru/post/1684282/


All Articles