Allow only positive decimal numbers

前端 未结 5 1195
北海茫月
北海茫月 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:14

    Assuming this is your product model, and you want to add non-negative constraint on price field. You can add the meta constraint on the model:

    class Product(models.Model):
        price = models.DecimalField(max_digits=13, decimal_places=2)
        created_at = models.DateTimeField(auto_now_add=True)
        updated_at = models.DateTimeField(auto_now=True)
    
        class Meta:
            managed = True
            db_table = 'product'
            constraints = [
                models.CheckConstraint(check=models.Q(price__gte='0'), name='product_price_non_negative'),
            ]
    

提交回复
热议问题