Within my Django models I have created a decimal field like this:
price = models.DecimalField(_(u\'Price\'), decimal_places=2, max_digits=12)
O
In Django 2.2 you can add constraints to a model which will be applied in the migrations as a constraint on the database table:
from decimal import Decimal
from django.db import models
class Item(models.Model):
price = models.DecimalField( _(u'Price'), decimal_places=2, max_digits=12 )
class Meta:
constraints = [
models.CheckConstraint(check=models.Q(price__gt=Decimal('0')), name='price_gt_0'),
]
Note:
Validation of Constraints
In general constraints are not checked during
full_clean()
, and do not raiseValidationErrors
. Rather you’ll get a database integrity error onsave()
.