set value for a column with dynamic name in python sqlalchemy

你说的曾经没有我的故事 提交于 2021-02-07 18:42:47

问题


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:


You can use the built-in setattr():

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


来源:https://stackoverflow.com/questions/34563200/set-value-for-a-column-with-dynamic-name-in-python-sqlalchemy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!