首页 > 解决方案 > 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最终返回过多的尾随零,然后验证失败。

可以用它做什么?

标签: pythondjangodjango-models

解决方案


您必须将值作为字符串而不是浮点数传递。看一下这个

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")

推荐阅读