如何创建具有最大和最小限制的Django FloatField? [英] How to create a Django FloatField with maximum and minimum limits?
问题描述
我正在Django模型中存储一些浮点数据,并且只有一定范围的值才有意义。因此,我想在模型和SQL约束级别上施加这些限制。
I'm storing some floating-point data in my Django models, and only a certain range of values are meaningful. Therefore, I'd like to impose these limits at both the model and SQL constraint level.
例如,我想做这样的事情:
For example, I'd like to do something like this:
class Foo(Model):
myfloat = FloatField(min=0.0, max=1.0)
我想在模型级别而不是表单级别执行此操作。实际上,我可能希望表单级别具有不同的范围。例如,在表单级别使用百分比[0,100],但在模型中将其转换为[0,1]。
I want to do this at the model level, not the form level. In fact, I might like the form level to have a different range; e.g., use percentages [0,100] at the form level but translate to [0,1] in the model.
这是否可行?如果可以,我该怎么做
Is this possible, and if so, how would I go about doing it?
推荐答案
到目前为止的答案描述了如何使表单生效。您也可以将验证器放入模型中。使用 MinValueValidator 和 MaxValueValidator 。
The answers so far describe how to make forms validate. You can also put validators in the model. Use MinValueValidator and MaxValueValidator.
例如:
from django.core.validators import MaxValueValidator, MinValueValidator
...
weight = models.FloatField(
validators=[MinValueValidator(0.9), MaxValueValidator(58)],
)
我不认为这会增加SQL约束。
I don't think that adds SQL constraints, tho.
这篇关于如何创建具有最大和最小限制的Django FloatField?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!