Allow only positive decimal numbers

前端 未结 5 1186
北海茫月
北海茫月 2021-02-01 13:48

Within my Django models I have created a decimal field like this:

price = models.DecimalField(_(u\'Price\'), decimal_places=2, max_digits=12)

O

5条回答
  •  温柔的废话
    2021-02-01 14:05

    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 raise ValidationErrors. Rather you’ll get a database integrity error on save().

提交回复
热议问题