Django set range for integer model field as constraint

后端 未结 4 1202
误落风尘
误落风尘 2020-12-15 15:51

I have a django model,

class MyModel(models.Model)
    qty = model.IntegerField()

where I want to set constraint for qty somet

4条回答
  •  有刺的猬
    2020-12-15 16:14

    You will have to create a custom validator

    from django.core.exceptions import ValidationError
    
    def validate_number(value):
        if something :  # Your conditions here
            raise ValidationError('%s some error message' % value)
    

    And then use this validator in your model

    from django.db import models
    
    class MyModel(models.Model):
        field = models.IntegerField(validators=[validate_number])
    

提交回复
热议问题