15

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

Anuj
  • 1,203
  • 3
  • 13
  • 20

1 Answers1

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

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

Community
  • 1
  • 1
AdamKG
  • 13,678
  • 3
  • 38
  • 46
  • I want to update a particular row, which I will get via some condition: team = Teams.objects.get(user=username). What I generally do is team.column_name='my new value' and then team.save(). But this will obviously wont work. And what I could see is that kwargs work only in function calls. So how does I implement my scenario? – Anuj Jan 25 '12 at 22:37
  • 4
    `setattr(team, column_name, "my new value")`. And: [docs on `setattr()`](http://docs.python.org/library/functions.html#setattr) – AdamKG Jan 25 '12 at 22:45
  • 1
    For the sake of completeness, you could also do `Team.objects.filter(id=team.id).update(**{column_name: "my new value"})`. – AdamKG Jan 25 '12 at 22:48