Home > Blockchain >  Django DecimalField rejecting all values with 2 and more decimal places
Django DecimalField rejecting all values with 2 and more decimal places

Time:08-05

I have a model:

class Account(models.Model):
    profile = models.ForeignKey(Profile, on_delete=models.CASCADE)
    balance = models.DecimalField(max_digits=10, decimal_places=2, default=0.00)

with a test:

@pytest.mark.django_db
class TestAccount:
    def test_it_accepts_valid_data(self):
        data = {"profile_id": create_profile().id, "balance": 10.55}

        account = Account(**data)
        account.full_clean()
        account.save()

Which fails with the exception:

FAILED wallets/tests/test_model.py::TestAccount::test_models - django.core.exceptions.ValidationError: {'balance': ['Ensure that there are no more than 2 decimal places.']}

Reducing the test balance to a one decimal place figure e.g 10.5 passes the test. The interesting part is increasing the decimal_places argument to a higher figure e.g 5, still raises the exception on any figure with more than one decimal place

Am I missing something or is this a Django bug? I'm on python3.9 and Django 4.0.6

CodePudding user response:

A float value of 10.55 is actually stored as 10.55000019073486328125, you might have to explicitly state that the 10.55 is a decimal value like Decimal('10.55') instead of allowing it to remain a float

  • Related