Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

set value for a column with dynamic name in python sqlalchemy

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!

like image 205
qkhhly Avatar asked Mar 13 '23 17:03

qkhhly


1 Answers

You can use the built-in setattr():

a = entry()
for col in ['summary', 'content', 'description']:
    setattr(a, col, get_value(col))
like image 61
alecxe Avatar answered Mar 23 '23 15:03

alecxe