django结合models.DecimalField和forms -> 错误:量化结果在当前上下文中位数过多
我想把一个模型中的小数字段和一个表单中的选择字段结合起来。
模型中的字段是:
sum = models.DecimalField(max_digits=2, decimal_places=2)
表单中的字段是:
sum = forms.ChoiceField(choices=WORK_HOUR_CHOICES, label='Sum Working Hours', required=True)
可选项是:
WORK_HOUR_CHOICES = (
(0, '0'),
(0.5, '0.5'),
(1, '1'),
(1.5, '1.5'),
(2, '2'),
(2.5, '2.5')
)
但是每次我想存储一个带小数的值时,都会出现这个错误:
quantize result has too many digits for current context
当我保存0或1时,一切都正常。
这是怎么回事呢?
1 个回答
6
这只是我的猜测,但我觉得你需要在这里放入小数:
WORK_HOUR_CHOICES = (
(Decimal("0"), '0'),
(Decimal("0.5"), '0.5'),
(Decimal("1"), '1'),
(Decimal("1.5"), '1.5'),
(Decimal("2"), '2'),
(Decimal("2.5"), '2.5')
)
你不能用浮点数直接初始化一个小数,必须用字符串来做。
>>> from decimal import Decimal
>>> Decimal(1.5)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\software\Python25\lib\decimal.py", line 578, in __new__
"First convert the float to a string")
TypeError: Cannot convert float to Decimal. First convert the float to a string
>>> Decimal("1.5")
Decimal("1.5")