There are two options. The first is to create a method for dynamic search, but use a decorator propertyso that other code can still use direct access to the attributes.
class MyModel(models.Model):
_first_name = models.CharField(max_length=100, db_column='first_name')
@property
def first_name(self):
return self._first_name or self.user.first_name
@first_name.setter
def first_name(self, value):
self._first_name = value
This always refers to the last value of first_name, even if the associated User has changed. You can get / set the property in the same way as for the attribute:myinstance.first_name = 'daniel'
Another option is to override the model method save()so that it performs a search while saving:
def save(self, *args, **kwargs):
if not self.first_name:
self.first_name = self.user.first_name
super(MyModel, self).save(*args, **kwargs)
, db, - , User , , .