I'd like to shorten the following code from
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)
to something like:
if field in list:
model_instance.update(field=value)
So I'm just wondering if it's possible.
You can just unpack into keyword arguments:
model_instance.update(**{field: value})
There is also an option to set the model field value and then save (there are though differences):
setattr(model_instance, field, value)
model_instance.save()
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments