I'm a bit confused here.
I wrote a custom model field called PriceField
that returns an instance of my class Price
from its from_db_value
and to_python
methods, which both convert from strings to instances of Price
.
My db_type
method returns "string"
because I want values of the field to be represented as strings in the database.
When I go to add a model that contains a PriceField
to the database, I'm getting InterfaceError: binding parameter 3
. The params
value for the sql statement is
[1,
'test',
'desc',
<utils.Price object at 0x7f159d9e6da0>,
'2019-02-22 00:39:31.634898',
'FS',
True,
True,
True,
True,
True,
'',
'']
I'm pretty sure that <utils.Price object at 0x7f159d9e6da0>
is my problem- how do I get that converted to a string so the database can accept it? I already have __str__
methods for my Price
and PriceField
classes.
Here are my 2 classes:
class Price():
units = None
value = 0
def __init__(self, units, value):
if not type(units) is PaymentUnit:
# TODO: Throw the right exception here
return;
self.units = units;
self.value = value;
def __str__(self):
return self.units.symbol + str(self.value)
class PriceField(models.Field):
units = '⧫'
value = 1
def __init__(self, value = 1, units='⧫', *args, **kwargs):
self.value = value;
self.units = units;
# Pass the values to the super class constructor
# Up to 16 digits, plus a decimal and up to 8 decimal
# digits (0.00000001 BTC is 1 satoshi)
kwargs['max_length'] = 24;
kwargs['help_text'] = 'Represents a price in a specific currency.';
kwargs['default'] = '⧫1'
super().__init__(*args, **kwargs)
def deconstruct(self):
name, path, args, kwargs = super().deconstruct()
del kwargs['max_length']
if self.units != '⧫':
kwargs['units'] = self.units
if self.value != 1:
kwargs['value'] = self.value
return name, path, args, kwargs
def db_type(self, connection):
return 'string'
def from_db_value(self, value, expression, connection):
if value is None:
return None
return parse_price(value);
def to_python(self, value):
if isinstance(value, Price):
return value
elif value is None:
return None
else:
return parse_price(value)
def __str__(self):
return "{0}{1}".format(self.units.symbol, self.value)