I have a variable say, column_name. I want to update a column whose name is saved in the variable column_name.
For example: I have a table with columns as: a, b, c, ..., z. column_name store either of these values. So I want to update that particular column which is saved in the variable column_name.
Thanks Anuj
Use update_fields in save() If you would like to explicitly mention only those columns that you want to be updated, you can do so using the update_fields parameter while calling the save() method. You can also choose to update multiple columns by passing more field names in the update_fields list.
The doc says: If the object's primary key attribute is set to a value that evaluates to True (i.e. a value other than None or the empty string), Django executes an UPDATE. If the object's primary key attribute is not set or if the UPDATE didn't update anything, Django executes an INSERT link.
To save data in Django, you normally use . save() on a model instance. However the ORM also provides a . update() method on queryset objects.
Model.objects.update(**{column_name: "my new value"})
See also:
https://stackoverflow.com/a/2921893/16361
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With