Home > Mobile >  How to pass a variable as an object instance in Django function
How to pass a variable as an object instance in Django function

Time:05-20

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)

CodePudding user response:

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()
    ...
  • Related