python - Django 奇怪的 DecimalField 验证
问题描述
当不应该提出验证错误时,我得到了验证错误。这是示例:
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)
显然,DjangoDecimalField
使用了错误的实现,to_python
最终返回过多的尾随零,然后验证失败。
可以用它做什么?
解决方案
您必须将值作为字符串而不是浮点数传递。看一下这个
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 - 如何保存和编辑服务器渲染数据?
- react-native - Apollo-Client refetch - TypeError: undefined is not an object
- python-3.x - 根据 git 分支编写日志消息?
- reactjs - react-spring 和 react-intersection-observer - 大量的重新渲染
- nestjs - NestJS - 使用 DotEnv
- ios - iOS UNNotificationServiceExtension - 如何修复配置文件问题?
- scipy - scipy.special 为合流超几何函数产生波动的结果
- java - Java:如何使用 Swing 和 super.paintChildren(g) 为数独求解器设置网格
- r - 如何规范化 R 中的数据
- c# - 我尝试在 Unity С# 项目框架 4.6.1 中设置,但保存项目后返回 4.7.1