只允许正数

2024-05-23 15:38:30 发布

您现在位置:Python中文网/ 问答频道 /正文

在我的Django模型中,我创建了一个十进制字段,如下所示:

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

显然,价格为负或为零是没有意义的。有没有办法把十进制数限制为正数?

或者我必须使用表单验证捕获它吗?


Tags: django模型表单models价格pricemax意义
3条回答

使用^{}

price = models.DecimalField(_(u'Price'), decimal_places=2, max_digits=12, validators=[MinValueValidator(Decimal('0.01'))])

根据文档,似乎没有办法在字段上设置数据库约束。最好是添加模型“验证器”,如果调用模型验证或使用ModelForm,则将调用该验证器。如果只将值放入对象并save(),则跳过验证程序。

因此,您可以在表单上添加验证,也可以在模型中添加验证,如果您使用ModelForm,该模型也可以在表单级别运行。

docs on "How validators are run"

See the form validation for more information on how validators are run in forms, and Validating objects for how they’re run in models. Note that validators will not be run automatically when you save a model, but if you are using a ModelForm, it will run your validators on any fields that are included in your form. See the ModelForm documentation for information on how model validation interacts with forms.

你可以这样做:

# .....
class priceForm(ModelForm):
    price = forms.DecimalField(required=False, max_digits=6, min_value=0)

这也对“price”的验证器值负责。

相关问题 更多 >