4

I have the following defined table in Python sqlalchemy:

class entry(Base):
    summary = Column(String(10000))
    content = Column(String(10000))
    description = Column(String(10000))

And I basically want to do the following:

a = entry()
for col in ['summary', 'content', 'description']:
    a[col] = get_value(col)

But I got the following error:

TypeError: 'entry' object has no attribute '__getitem__'

So I guess I cannot treat a as a dict. Looking through sqlalchemy document, I didn't figure out a way to set the value of a Column when using a variable to identify the Column. Could anyone point me to the right direction? Thank you for the help!

1 Answer 1

9

You can use the built-in setattr():

a = entry()
for col in ['summary', 'content', 'description']:
    setattr(a, col, get_value(col))
Sign up to request clarification or add additional context in comments.

1 Comment

Keep in mind this will not raise any exception if you try to set a column that does not exist in the model.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.