python - django 将 models.DecimalField 与表单结合起来 -> 错误 : quantize result has too many digits for current context

标签 python django

我想将模型十进制字段与表单选择字段组合起来。

模型中的字段:

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/

相关文章:

python - 使用 apply lambda 和 str 从 python 中的列获取子字符串

python - 暂停执行,直到从 tkinter 窗口收到用户输入

python - Django + GoogleAppEngine 错误 : DJANGO_SETTINGS_MODULE is undefined

python - Django 上不必要的自动迁移?

python - 在 Django 测试框架中使用 Basic HTTP 访问认证

python - 害怕 "not the same object error" pickle 一个 queryset.query 对象

python - 如何获得多列分组 Pandas 的最大值?

python - 无法使用此代码基于python open cv录制视频

python - Django休息框架: serializer does not include id field in response data

python - 如何计算 pandas 数据框中的标准差?