0

I have the model below:

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')

What I am trying to do is that based on the data selected in 'type' field, the '_value' field will check the input and convert it to the desired type. I was told using django @property could do this, but I'm not sure how it works together.

So far, I have tried this just to test, but to no avail:

@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

If anyone has an idea or can lead me in the right direction, I will appreciate it.

user875139
  • 1,599
  • 4
  • 23
  • 44

1 Answers1

1

I'm not sure what that test is supposed to demonstrate. If you want to convert a value based on the value of another field, do that in the getter; you don't need a setter.

@property
def value(self):
    conversions = {'int': int, 'str': str, 'bool': bool, 'float': float}
    return conversions[self.type](self._value)
Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
  • Thank you Daniel it worked. Could you explain why the conversions dict is necessary and what is a good attribute error to look for if I wanted to create a try/catch? – user875139 Nov 12 '18 at 13:43
  • 1
    It's not necessary, you could do a series of if/elif statements - but the point is the value of `self.type` is a string, you need to get from there to the actual type methods themselves. A dict will raise a KeyError if the lookup is not found. – Daniel Roseman Nov 12 '18 at 13:47