简体   繁体   中英

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.

You can do this:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM