我想访问和更新查询的结果。
SQLAlchemy通过使用row.field来提供这一点。
但是,我想使用一个循环,它包含要作为文本更改的字段的名称。
当字段为"the_name_of_the_field“时,如何更新the_name_of_the_field?
row = session.query(...).filter(...)
many_fields = {"foo": "all_fields_updated", "bar": "all_fields_updated"}
for field in many_fields
row.field = "all fields updated"
session.commit()显然,行row.field抛出一个错误,因为它试图访问字段“字段”,而不是dict中声明的"foo“或"bar”。
AttributeError:“结果”对象没有属性“字段”
我无法将查询结果转换为dict(),因为session.commit()将不再检测它。
在使用此命令时,我遇到了相同的问题:
table.update().\
where(...).\
values(field="all_fields_updated")因为我不能将变量作为“字段”变量传递。我希望过高考虑这个问题,但我现在似乎还没有找到解决这个问题的办法。任何解决办法/想法都值得赞赏。
发布于 2019-09-02 12:07:00
可以使用setattr根据字符串设置属性。例如,在您的案例中:
row = session.query(User).first()
many_fields = {"foo": "all_fields_updated", "bar": "all_fields_updated"}
for key, value in many_fields.items():
setattr(row, key, value)
session.commit()https://stackoverflow.com/questions/57756475
复制相似问题