【发布时间】:2021-12-28 23:02:32
【问题描述】:
在一个 django 项目中,我试图存储一个计算得出的十进制值,但由于某些奇怪的原因它失败了。我的模型看起来像:
class FancyModel(models.Model):
fancy_field = models.DecimalField(max_digits=10, decimal_places=3, null=True, blank=True)
有时,实际上经常会在保存时崩溃:
django.db.utils.IntegrityError: CHECK constraint failed: myapp_fancy_model
我在一些挖掘之后发现是由这个验证引起的:
django.core.exceptions.ValidationError: {'fancy_field': ['Ensure that there are no more than 2 decimal places.']}
我已经转储了实际模型的值,我觉得还可以:
{'fancy_field': 3.26 }
我看不出这会如何失败。有时它工作正常,有时它崩溃。我尝试使用round-方法,例如:
model_instance.fancy_model = round(floating_value, 2)
但它仍然失败。
【问题讨论】:
-
你能分享一个完整的回溯和你触发错误的视图/函数/代码吗?
-
也许问题在于使用
float而不是Decimal?您是否尝试将fancy_field值包装到Decimal(float_value)上?
标签: python django floating-point decimal rounding