在python sqlalchemy中为具有动态名称的列设置值

2024-01-10

我在 Python sqlalchemy 中有以下定义的表:

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

我基本上想做以下事情:

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

但我收到以下错误:

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

所以我想我无法治疗a as a dict。翻阅sqlalchemy文档,我没有找到设置a值的方法Column当使用变量来标识Column。有人能指出我正确的方向吗?感谢您的帮助!


您可以使用内置的setattr() https://docs.python.org/2/library/functions.html#setattr:

a = entry()
for col in ['summary', 'content', 'description']:
    setattr(a, col, get_value(col))
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在python sqlalchemy中为具有动态名称的列设置值 的相关文章

随机推荐