【问题标题】:Why is Django trying to insert infinite decimal places into my decimal field?为什么 Django 试图在我的十进制字段中插入无限小数位?
【发布时间】:2021-05-16 03:32:39
【问题描述】:

我有这个模型:

class ErrorReproduction(models.Model):
    amount = models.DecimalField(primary_key=True, max_digits=65535, decimal_places=65535)

    class Meta:
        managed = False
        db_table = 'error_reproduction'

在我看来,我正在运行ErrorReproduction.objects.create(amount=1.0),这给了我错误[<class 'decimal.InvalidOperation'>]

然后我看了this post,上面说max_digits应该大于decimal_places,所以我把模型改成这样:

class ErrorReproduction(models.Model):
    amount = models.DecimalField(primary_key=True, max_digits=65535, decimal_places=32000)

    class Meta:
        managed = False
        db_table = 'error_reproduction'

现在,视图中的相同操作给了我:

value overflows numeric format
LINE 1: ...SERT INTO "error_reproduction" ("amount") VALUES ('1.0000000...
                                                             ^

为什么值 1.0 会溢出十进制字段?是因为无限.00000吗?我应该如何将值插入十进制字段?

我也试过了:

  • ErrorReproduction.objects.create(amount=1)
  • ErrorReproduction.objects.create(amount=Decimal(1.0))
  • ErrorReproduction.objects.create(amount=Decimal(1))
  • ErrorReproduction.objects.create(amount=float(1.0))
  • ErrorReproduction.objects.create(amount=float(1))
  • ErrorReproduction.objects.create(amount=math.trunc(1.0))
  • ErrorReproduction.objects.create(amount=math.trunc(1))
  • ErrorReproduction.objects.create(amount=round(1.0, 3))
  • ErrorReproduction.objects.create(amount=round(1, 3))

【问题讨论】:

    标签: python django django-models


    【解决方案1】:

    我想通了,我使用manage.py inspectdb 生成模型,这让我假设 Django 给我的默认 65535 位小数可以由 postgres 处理,但 postgres 的 numeric data type 仅存储小数点后 16383 位点。

    显然,当 Django 存储小数时,它实际上存储了每个小数位,因此它试图在我给它的 1.0 值中存储所有 65,535 个零。

    将模型更改为:

    class ErrorReproduction(models.Model):
        amount = models.DecimalField(primary_key=True, max_digits=15000, decimal_places=10000)
    
        class Meta:
            managed = False
            db_table = 'error_reproduction'
    

    解决问题。

    【讨论】:

      猜你喜欢
      • 2011-02-07
      • 2018-03-10
      • 2022-08-19
      • 2023-04-01
      • 1970-01-01
      • 2019-11-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多