approximation = models.IntegerField(null=False, default=None)
I need to validate this field. It should be greater than 0 but i don't want to make function.
CodePudding user response:
If the value has to be greater or equal to zero, you can use PositiveIntegerField
instead of IntegerField
.
If the value has to be strictly greater than zero, you can add a validator:
from django.core.validators import MinValueValidator
from django.db import models
approximation = models.IntegerField(
null=False,
default=None,
validators=[MinValueValidator(0)],
)
CodePudding user response:
Add Meta class as follows:
from django.db import models
class Example(models.Model):
approximation = models.IntegerField(null=False, default=None)
class Meta:
constraints = [
models.CheckConstraint(check=models.Q(approximation__gt=0), name='approximation_gt_0'),
]
Sources:
This will add a Check constraint into your database.