Django set range for integer model field as constraint

后端 未结 4 1204
误落风尘
误落风尘 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: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.

    0 讨论(0)
  • 2020-12-15 16:13

    Since Django 2.2 you can enforce the constraints on a database level with CheckConstraint:

    from django.db import models
    
    class MyModel(models.Model)
        qty = model.IntegerField()
    
        class Meta:
            constraints = [
                models.CheckConstraint(
                    check=models.Q(qty__gte=1) & models.Q(qt__lte=10),
                    name="A qty value is valid between 1 and 10",
                )
            ]
    
    
    0 讨论(0)
  • 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])
    
    0 讨论(0)
  • 2020-12-15 16:17

    If you are using postgres, you can use range fields to specify the range. Check this: Range Fields in django

    0 讨论(0)
提交回复
热议问题