我想从
缩短以下代码if field == 'favorite_food':
model_instance.update(favorite_food=value)
elif field == 'favorite_drink':
model_instance.update(favorite_drink=value)
elif field == 'favorite_color':
model_instance.update(favorite_color=value)
类似于:
if field in list:
model_instance.update(field=value)
所以我只是想知道它是否可能。
答案 0 :(得分:2)
你可以unpack into keyword arguments:
model_instance.update(**{field: value})
还可以选择设置模型字段值然后保存(虽然有differences):
setattr(model_instance, field, value)
model_instance.save()
答案 1 :(得分:0)
你可以这样做
fields = ["favorite_food", "favorite_drink", "favorite_color"]
field = "favorite_food"
if field in fields:
model_instance.update(field=value)