我有以下模型:
class Actor(Model):
VALUE_CHOICES = (
('int', 'Integer'),
('str', 'String'),
('float', 'Float'),
('bool', 'Boolean')
)
type = models.CharField(max_length=5, choices=VALUE_CHOICES, default='str')
_value = models.CharField(max_length=100, default='', db_column='value')
我想要做的是根据在'type'字段中选择的数据,'_ value'字段将检查输入并将其转换为所需的类型。我被告知使用django @property可以做到这一点,但我不确定它是如何协同工作的。
到目前为止,我试过这只是为了测试,但无济于事:
@property
def value(self):
return self._value
@value.setter
def value(self, val):
print('This is self ', self, ' and val is ', val, ' and this is self ', self.request)
self._value = val
如果有人有想法或能带领我朝着正确的方向前进,我将不胜感激。
我不确定该测试应该展示什么。如果要根据另一个字段的值转换值,请在getter中执行此操作;你不需要一个二传手。
@property
def value(self):
conversions = {'int': int, 'str': str, 'bool': bool, 'float': float}
return conversions[self.type](self._value)