Django Models: Override a field return value

django, field, model, overriding

Solution

Yes, you can use properties to do this

class ModelA(models.Model)
    _name = models.CharField(...)

    def set_name(self, val):
        self._name = "%s - foo" % val

    def get_name(self):
        return self._name

    name = property(get_name, set_name)

Problem

I'm wondering if it is possible to override the default value of a field when it is returned. Say I had a model: ``` class ModelA(models.Model) name = models.CharField(max_length=30) ``` Is there any way that calling ``` modela_instance.name ``` can return a modified value, for example name + " foo", but have the code that appends foo run by default within the model itself, so all I would need to do is call name to get the appended value? I should elaborate and say that what I'm actually hoping to do is have a method within the model: ``` def get_name(self): return self.name + " foo" ``` or similar, and just want that get_name method to override the call to the field "name".

Original source

Related problems