自定义模型字段在哪里转换为它们的db_type?

时间:2019-02-22 00:47:11

标签: python django django-models django-model-field

我有点困惑。

我编写了一个名为PriceField的自定义模型字段,该字段从其Pricefrom_db_value方法返回我的类to_python的实例,它们都从字符串转换为Price

我的db_type方法返回"string",因为我希望在数据库中将该字段的值表示为字符串。

当我向数据库添加包含PriceField的模型时,我得到InterfaceError: binding parameter 3。 sql语句的params值为

[1,
 'test',
 'desc',
 <utils.Price object at 0x7f159d9e6da0>,
 '2019-02-22 00:39:31.634898',
 'FS',
 True,
 True,
 True,
 True,
 True,
 '',
 '']

我非常确定<utils.Price object at 0x7f159d9e6da0>是我的问题-如何将其转换为字符串,以便数据库可以接受它?我的__str__Price类已经有PriceField个方法。

这是我的2个班级:

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)

0 个答案:

没有答案