为什么Django试图在我的小数字段中插入无限小数位?

2024-09-30 18:32:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这个模型:

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_位应该大于decimal_位,所以我将模型改为:

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

Tags: key模型modelobjectsmodelscreateerroramount
1条回答
网友
1楼 · 发布于 2024-09-30 18:32:49

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

显然,当Django存储小数时,它实际上存储每个小数点,所以它试图将所有65535个零存储在我给它的1.0值中

将模型更改为:

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

    class Meta:
        managed = False
        db_table = 'error_reproduction'

解决了这个问题

相关问题 更多 >