Adding Custom Django Model Validation

前端 未结 4 1922
我寻月下人不归
我寻月下人不归 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:33

    I think this can help you, We can create multiple validators like this use in models.

    from django.core.exceptions import ValidationError
    from django.utils.translation import gettext_lazy as _
    from django.db import models
    
    def validate_even(value):
        if value % 2 != 0:
            raise ValidationError(
                _('%(value)s is not an even number'),
                params={'value': value},
            )
    
    class MyModel(models.Model):
        even_field = models.IntegerField(validators=[validate_even])
    

提交回复
热议问题