[英]Django DecimalField generating “quantize result has too many digits for current context” error on save
[英]django combine models.DecimalField with forms -> error: quantize result has too many digits for current context
我想将模型十进制字段与表单选择字段组合在一起。
模型中的字段:
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时,它工作正常。
怎么了?
只是一个猜测,但是我敢打赌,您需要在其中放入Decimals:
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')
)
您不能使用浮点常量初始化Decimal,而必须使用字符串。
>>> 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")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.