I’m trying to force Django to always store numbers with 2 decimal places but if the number is a whole one then it isn’t store the .00
def clean_myfield(self):
data = self.cleaned_data['myfield']
self.cleandecimal(data)
return data
def cleandecimal(self, data):
data = Decimal(data).quantize(Decimal('.01'), rounding=ROUND_DOWN)
print 'data ', data
return data
My prints always display as intended e.g. 4.00 but that gets stored as 4
How can I override the save method to store the value without rounding it?
Its a representation issue. Decimal number stores numbers, not representations of them. Mathematically
1.00is equal to1. So its possible that your database backend stores smallest truncated decimal without all zeros – so it’s probably not Django, but db. If you want to force Django to always return decimal with two decimal places, you can overwrite the DecimalField:This will always return numbers with
decimal_placesas specified. You can use it the same way as you would normalDecimalField, like: