1

To make some code more generic, I'm trying to retrieve/set values in a database row using the Column object.

For example, I'll have this setup:

col = MyTable.MyColumn
result = session.query(...).one()

Now I want to get/set the values, semantically like below:

cur_value = result[col]
result[col] = new_value

What is the correct syntax to use the Column object to get/set values in the result?

col will not be a static value, but dynamically taken from a map.

edA-qa mort-ora-y
  • 30,295
  • 39
  • 137
  • 267
  • `cur_value =result.col, result.col = new_val db.session.commit()` als this may help https://stackoverflow.com/questions/9667138/how-to-update-sqlalchemy-row-entry – sahasrara62 Dec 02 '20 at 11:31

1 Answers1

1

You can do this:

cur_value = getattr(result, col.key)
setattr(result, col.key, new_value)
Mehrdad Pedramfar
  • 10,941
  • 4
  • 38
  • 59