I have a model that holds user address. This model has to have first_name and last_name fields since one would like to set address to a recipient (like his company, etc.). What I’m trying to achieve is:
- If the
first_name/last_namefield in the address is filled – return simply that field - If the
first_name/last_namefield in the address is empty – fetch the corrresponding field data from a foreignkey pointing to a properdjango.auth.models.User - I’d like this to be treated as normal Django field that would be present in fields lookup
- I don’t want to create a method, since it’s a refactoring and
Address.first_name/last_nameare used in various places in the application (also in model forms, etc.), so I need this to me as smooth as possible, or else, I will have to tinker around in a lot of places.
There are two options here. The first is to create a method to look it up dynamically, but use the
propertydecorator so that other code can still use straight attribute access.This will always refer to the latest value of first_name, even if the related User is changed. You can get/set the property exactly as you would an attribute:
myinstance.first_name = 'daniel'The other option is to override the model’s
save()method so that it does the lookup when you save:This way you don’t have to change your db, but it is only refreshed on save – so if the related User object is changed but this object isn’t, it will refer to the old User value.