Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: updating a column, saved in a variable name

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

like image 414
Anuj Avatar asked Jan 25 '12 21:01

Anuj


People also ask

How do I update a specific field in Django?

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.

How Django knows to update VS insert?

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.

How do I save changes in Django model?

To save data in Django, you normally use . save() on a model instance. However the ORM also provides a . update() method on queryset objects.


1 Answers

Model.objects.update(**{column_name: "my new value"})

See also:
https://stackoverflow.com/a/2921893/16361

like image 145
AdamKG Avatar answered Sep 18 '22 05:09

AdamKG