Adding Custom Django Model Validation

前端 未结 4 1915
我寻月下人不归
我寻月下人不归 2020-12-07 14:15

I have a Django model with a start and end date range. I want to enforce validation so that no two records have overlapping date ranges. What\'s the simplest way to implemen

4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-07 14:23

    I think you should use this: https://docs.djangoproject.com/en/dev/ref/models/instances/#validating-objects

    Just define clean() method in your model like this: (example from the docs link)

    def clean(self):
        from django.core.exceptions import ValidationError
        # Don't allow draft entries to have a pub_date.
        if self.status == 'draft' and self.pub_date is not None:
            raise ValidationError('Draft entries may not have a publication date.')
        # Set the pub_date for published items if it hasn't been set already.
        if self.status == 'published' and self.pub_date is None:
            self.pub_date = datetime.datetime.now()
    

提交回复
热议问题