您如何更新Sqlalchemy RowProxy



我正在使用sqlalchemy表达语言(不是ORM(,我正在尝试弄清楚如何更新查询结果。

我发现RowProxy对象不支持分配,而是扔AttributeError

# Get a row from the table
row = engine.execute(mytable.select().limit(1)).fetchone()
# Check that `foo` exists on the row
assert row.foo is None
# Try to update `foo`
row.foo = "bar"
AttributeError: 'RowProxy' object has no attribute 'foo'

我找到了使用ORM的解决方案,但是我专门使用表达式语言。

我还找到了这个解决方案,该解决方案将行转换为dict并更新了dict,但这似乎是一个骇客的解决方法。

所以我有几个问题:

  • 这实际上是唯一的做法吗?
  • 此外,这是推荐的做到这一点的方法吗?
  • 最后,缺乏文档使我感到奇怪:我只是试图这样做滥用sqlalchemy吗?

您正在滥用sqlalchemy。您描述的用法是使用ORM的好处。如果您只想将自己限制在Sqlalchemy Core中,那么您需要做

engine.execute(mytable.update().where(mytable.c.id == <id>).values(foo="bar"))

最新更新