如何在 Django 函数中将变量作为对象实例传递

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

我有一个功能

def update_field():
    ...
    ...
    book.country = country_id
    ...

我在好几个地方都有相同的代码,我需要为它创建一个单独的函数。例如

def update_field(obj_field):
    ...
    ...
    obj_field = country_id
    ...

但是当我尝试调用该函数时它不起作用

country = book.country
update_field(country)

setattr 可以完成这项工作

def update_field(obj, field_name):
    ...
    ...
    setattr(obj, field_name, country_id)
    ...

如果您想编辑相关的模型字段,您应该这样做:

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