【问题标题】:Django decimal field fails to store floating numbers that should be okDjango 十进制字段无法存储应该没问题的浮点数
【发布时间】: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


【解决方案1】:

注释掉所有代码,然后逐行添加后,我发现错误根本不是由小数域引起的,而是由一个负值的 PositiveIntegerField 引起的。 model.full_clean() 根本没有提到 PositiveIntegerField,所以这真的很奇怪。那是几个小时我不会回来的:-/

【讨论】:

    【解决方案2】:

    您应该考虑将传递的 decimal_places 参数从 3 更改为 2

    【讨论】:

    • 我试过了。尝试将 max_digits 设置为 30,将 decimal_places 设置为 15。没有任何帮助。
    猜你喜欢
    • 2010-11-03
    • 1970-01-01
    • 2010-09-22
    • 2012-09-24
    • 2019-03-05
    • 1970-01-01
    • 2018-03-08
    • 2014-01-06
    相关资源
    最近更新 更多