edA-qa mort-ora-y
edA-qa mort-ora-y

Reputation: 31871

How can I get/set an SqlAlchemy query value with the Column object

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.

Upvotes: 1

Views: 971

Answers (1)

Mehrdad Pedramfar
Mehrdad Pedramfar

Reputation: 11073

You can do this:

cur_value = getattr(result, col.key)
setattr(result, col.key, new_value)

Upvotes: 1

Related Questions