如何更新 SQLAlchemy RowProxy?

Car*_*way 5 sqlalchemy

我正在使用 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'
Run Code Online (Sandbox Code Playgroud)

我找到了这个解决方案,它使用了 ORM,但我特别希望使用表达式语言。

我还找到了这个解决方案,它将行转换为字典并更新字典,但这似乎是一个hacky 解决方法。

所以我有几个问题:

  • 这实际上是唯一的方法吗?
  • 此外,这是推荐的方法吗?
  • 最后,缺乏文档让我怀疑:我是否只是通过尝试这样做而滥用 SQLAlchemy?

uni*_*rio 4

您误用了 SQLAlchemy。您所描述的用法是使用 ORM 的好处。如果您只想限制自己使用 SQLAlchemy Core,那么您需要这样做

engine.execute(mytable.update().where(mytable.c.id == <id>).values(foo="bar"))
Run Code Online (Sandbox Code Playgroud)