Django: Is there a way to have a "date range unique"?

If my model is for elements:

class Item(models.Model):
    name = models.CharField(max_length=500)
    startDate = models.DateField("Start Date", unique="true")
    endDate = models.DateField("End Date")      

Each item must have a unique date range. for example, if I create an element with a date range from June 1 to June 8, how can I save an element with a date range from June 3 to June 5 after creation (or make a mistake with the template logic)?

PLEASE let me know if I can clarify this question better!

+3
source share
1 answer

You cannot force this at the model level, however you can override the save method for something like this:

class Item(models.Model):
    name = models.CharField(max_length=500)
    startDate = models.DateField("Start Date", unique="true")
    endDate = models.DateField("End Date")     

    def save(self, *args, **kwargs):
        try:
            Item.objects.get(Q(startDate__range=(self.startDate,self.endDate))|Q(endDate__range=(self.sartDate,self.endDate))|Q(startDate__lt=self.startDate,endDate__gt=self.endDate))
            #raise some save error
        except Item.DoesNotExist:
            super(Item,self).save(*args,**kwargs)

edit: , , , , :).

+6

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


All Articles