0

I had this model:

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

    class Meta:
        managed = False
        db_table = 'error_reproduction'

In my view, I was running ErrorReproduction.objects.create(amount=1.0), which gave me the error [<class 'decimal.InvalidOperation'>].

I then read this post, which said that max_digits should be greater than the decimal_places, so I changed the model to this:

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

    class Meta:
        managed = False
        db_table = 'error_reproduction'

Now, the same operation in the view gives me:

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

Why is the value 1.0 overflowing the decimal field? Is it because of the infinite .00000? How am I supposed to insert values into decimal fields?

I have also tried:

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

1 Answers1

0

I figured it out, I generated the models using manage.py inspectdb, which led me to assume that the default 65535 decimal places that Django gave me could be handled by postgres, but postgres's numeric data type only stores 16383 digits after the decimal point.

Evidently, when Django stores decimals, it stores literally every decimal place, so it was trying to store all 65,535 zeroes in the 1.0 value I gave it.

Changing the model to:

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

    class Meta:
        managed = False
        db_table = 'error_reproduction'

Fixes the issue.