user14819175
user14819175

Reputation:

Validate model field in single line

 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.

Upvotes: 0

Views: 79

Answers (2)

user14687465
user14687465

Reputation:

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:

Constraint option

Constraint reference

This will add a Check constraint into your database.

Upvotes: 0

Raida
Raida

Reputation: 1506

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)],
)

Upvotes: 1

Related Questions