我想将模型十进制字段与表单选择字段组合起来。
模型中的字段:
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 时,它工作正常。
出了什么问题?
最佳答案
这只是一个猜测,但我打赌你需要在其中输入小数:
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")
关于python - django 将 models.DecimalField 与表单结合起来 -> 错误 : quantize result has too many digits for current context,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2051575/