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?
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)
尝试使用decimal.Decimal代替float()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.