Possibility of having variable parameter names in Django model updates

crentagon

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.

alecxe

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.

edited at
0

Comments

0 comments
Login to comment

Related

Variable parameter lists: possibility to collect them in variable?

Django model property with parameter

How do I having one model listen for updates of another?

Having the variable names in func_get_args()

Django model.save() doing inconsistent updates

django - view that creates or updates a model but requires a submit

How to output an API having names different than variable names?

Static variable and parameter having the same name

Having parameter (constant) variable with NaN value in FORTRAN

Django : Increase variable in the model

Django - Having trouble using foreign key model

Django, having Q object filter by function in model

Django context variable names for the templates

What is the point of having two different names for the same parameter?

Django - Appending model parameter to url

ui-sref and variable state parameter names

Export tensorflow model to ONNX and specify variable names

Having a global variable available to your templates in Django

Dapper.NET: should variable names be the same as parameter names?

Django mutliple same GET parameter names not working

Django how are filter parameter names named?

Reading 2 property files having same variable names in Spring

create django model with field names from list

Django: Get names of fields of a model class

Same model names in Django's project

Django get all foreign key names of a model

Django queryset get names of model fields

Angularjs ng-model updates the variable for input element not for div element

Sending input names in Django form having javascript code