1

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)

1 Answer 1

2

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()
    ...
Sign up to request clarification or add additional context in comments.

2 Comments

One more question How can I pass related model field? For example: obj=book and field_name=booktext.about
Thanks a lot for your help. Maybe, you can also help me with this question - stackoverflow.com/questions/72319251/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.