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.

1

1 Answer 1

1

You can do this:

cur_value = getattr(result, col.key)
setattr(result, col.key, new_value)
Sign up to request clarification or add additional context in comments.

2 Comments

The column objects are not strings, they are SqlAlchemy Column objects. If I knew how to get the resulting name of that column, this would work.
@edA-qamort-ora-y use: col = MyTable.MyColumn.key... this will give you your column name.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.