0

I have a model:

Model(models.Model)
    price = models.DecimalField(max_digits=10, decimal_places=2)

and I have a string:

new_price = "39.99"

When I try the following:

model_instance.price = float(new_price)
model_instance.save()

I get django.core.exceptions.ValidationError: {'price': ['Ensure that there are no more than 10 digits in total.']}

Why?

DDiran
  • 533
  • 1
  • 6
  • 23

2 Answers2

2

That has to do with Python's internal float representation's limitations. But you can use the string directly with a DecimalField:

model_instance.price = "39.99"
model_instance.save()

If you have dynamic input you can use decimal.Decimal directly to get the required precision:

from decimal import *

model_instance.price = Decimal(new_price).quantize(
    Decimal('0.01'), 
    rounding=ROUND_HALF_UP)
user2390182
  • 72,016
  • 6
  • 67
  • 89
  • That's what I tried the first time but it didn't work for some reason. – DDiran Nov 30 '17 at 10:59
  • Actually, specifying `model_instance.price = str(new_price)` did the trick, weird though as it was already a string! Thanks! – DDiran Nov 30 '17 at 11:01
0

Try using decimal.Decimal instead of float()

ziggy jones
  • 401
  • 2
  • 7