django结合models.DecimalField与表单 - >错误:量化结果有太多的数字用于当前上下文

Tho*_*mel 5 python django

我想将模型十进制字段与表单选择字段组合在一起.

模型中的字段:

sum = models.DecimalField(max_digits=2, decimal_places=2)
Run Code Online (Sandbox Code Playgroud)

表格中的字段:

sum = forms.ChoiceField(choices=WORK_HOUR_CHOICES, label='Sum Working Hours', required=True)
Run Code Online (Sandbox Code Playgroud)

选择:

WORK_HOUR_CHOICES = (
    (0, '0'),
    (0.5, '0.5'),
    (1, '1'),
    (1.5, '1.5'),
    (2, '2'),
    (2.5, '2.5')
)
Run Code Online (Sandbox Code Playgroud)

但总是当我想存储一个小数位的值时,我得到这个错误:

quantize result has too many digits for current context
Run Code Online (Sandbox Code Playgroud)

当我保存0或1时,它工作正常.

怎么了?

Set*_*eth 6

这只是猜测,但我打赌你需要把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')
)
Run Code Online (Sandbox Code Playgroud)

您不能使用浮点常量初始化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")
Run Code Online (Sandbox Code Playgroud)