Django奇怪的DecimalField验证

问题描述 投票:1回答:1

我不应该提出验证错误。这是一个例子:

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实现,它最后会返回过多的尾随零,然后验证失败。

怎么办呢?

python django django-models
1个回答
1
投票

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

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")
© www.soinside.com 2019 - 2024. All rights reserved.