Django set range for integer model field as constraint

后端 未结 4 1216
误落风尘
误落风尘 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条回答
  •  -上瘾入骨i
    2020-12-15 16:07

    You can use Django's built-in validators -

    from django.db import models
    from django.core.validators import MaxValueValidator, MinValueValidator
    
    class MyModel(models.Model):
        qty = models.IntegerField(
            default=1,
            validators=[MaxValueValidator(100), MinValueValidator(1)]
         )
    

    NOTE: The validators will not run automatically when you save a model, but if you are using a ModelForm, it will run your validators on the fields that are included in the form. Check this link for more info.

提交回复
热议问题