我想通过将我的类字段的名称传递给这个python函数来删除冗余代码,但我无法在python中解决如何传入此名称并在类变量解引用中使用它(在一个案例中)它是emplorate_id,另一个是business_code引用模型中的Code对象字段。
我传入两个不同的模型对象,并在我想引用的模型之一
model.emplorate_id
和另一个
model.business_code
所以我正在寻找一个可以传递的变量......类似于:
def my_func(model, code_type, variable_name):
model.(variable_name) = Code()
@staticmethod
def create_emplorate_id_if_needed(model, code_type):
"""
Creates the emplorate_id if the model field is missing
Would be nice to pass in the field name here if I knew python better
:param model: a model objects with an emplorate_id field
:return: boolean True if created
"""
model.code_type = code_type
## HACK-HACK -- i can't work out how to pass in the field name 'emplorate_id'
## or "business_code" here in python
if code_type == Code.CODE_TYPES.BUSINESS:
try:
model.emplorate_id
return False
except Code.DoesNotExist:
model.emplorate_id = Code()
model.emplorate_id.save(model)
return True
else:
try:
model.business_code
return False
except Code.DoesNotExist:
model.business_code = Code()
model.business_code.save(model)
return True