python - Django奇怪的DecimalField验证

标签 python django django-models

我收到了不应引发的验证错误。这是示例:

from django.db.models import DecimalField

f = DecimalField(max_digits=9, decimal_places=3)

# got validation error here
# `Ensure that there are no more than 3 decimal places`
f.clean(value=12.123, model_instance=None)

# returns Decimal('12.1230000')
f.to_python(12.123)

# this is absolutely fine
f.clean(value=123456.123, model_instance=None)

# returns Decimal('123456.123')
f.to_python(123456.123)

显然,Django DecimalField 使用了错误的 to_python 实现,它在末尾返回过多的尾随零,然后验证失败。

用它可以做什么?

最佳答案

您必须将值作为字符串而不是 float 传递。看看这个

from django.db.models import DecimalField

f = DecimalField(max_digits=9, decimal_places=3)
f.clean(value="12.123", model_instance=None)
f.to_python("12.123")
f.clean(value="123456.123", model_instance=None)
f.to_python("123456.123")

关于python - Django奇怪的DecimalField验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52376693/

相关文章:

python - 将实时数据发送到 Django 前端

django - 如何在不创建节点 ModelField 类的情况下重写单个字段的 __str__() 方法?

django - 如何在 Django 中显示关系值?

django - 原始查询必须包含主键

python - 为什么我的程序将 <function convert at 0x02DE8C00> 写入我的文件?

python - PySide Qt 在叶项中插入行并更新 View

python - 从 beautifulsoup 替换\n\t

python - ulr 不唯一的 pandas.read_html 的替代方案?

Django Allauth 如何更改用户名=名字?

django - 如何切换 Django OneToOneField 的方向?