I am trying to create a custom field in Django which will take a decimal currency value (example: £1.56) and save it in the database as an Integer (example: 156) to store currency values.
This is what I have so far (I have put fixed values to test)
class CurrencyField(models.DecimalField):
__metaclass__ = models.SubfieldBase
def get_internal_type(self):
return 'PositiveIntegerField'
def to_python(self, value):
print "CurrentField to_python"
return Decimal(value)/100
def get_db_prep_value(self, value, connection, prepared=False):
print "CurrentField get_db_prep_value"
if value is None:
return value
print type(value)
return int(value*100)
I am following the Python 1.7 documentation for creating custom model fields.
In the above code, the get_db_prep_value
method is never being called when I save the model using this field. The to_python
method is working fine (if I manually enter the value in the DB it will return the correct decimal), however it will never save the correct value.
I have also tried using get_prep_value
and this has the same result.
How can I make it save the correct value?