Issue
I have a function
def update_field():
...
...
book.country = country_id
...
I have the same piece of code in several places and I need to make a separate function for it. For example
def update_field(obj_field):
...
...
obj_field = country_id
...
but when I try to call the function it doesn't work
country = book.country
update_field(country)
Solution
setattr would do the job
def update_field(obj, field_name):
...
...
setattr(obj, field_name, country_id)
...
If you would want to edit related model field you should do:
def update_field(obj, field_name):
...
...
related_model_name, related_model_field_name = field_name.split('.')
related_model = getattr(obj, related_model_name)
setattr(related_model, related_model_field_name, 'Abba')
related_model.save()
...
Answered By - TrueGopnik
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.