如何在 SQLAlchemy 中编写生成更新
我只是使用 SQLAlchemy 核心,无法获取 sql 来允许我添加 where 子句。我希望这个非常通用的更新代码适用于我的所有表。目的是这是对应于每个表的通用插入/更新函数的一部分。通过这种方式,它允许极其简短的测试代码和简单的 CLI 实用程序,可以简单地传递所有参数和参数。选项,无需为每个表使用单独的子命令的复杂性。
还需要进行一些调整才能实现这一点,但现在应该可以很好地进行更新。然而,虽然 SQLAlchemy 指的是生成查询,但它并不区分选择和查询。更新。我查看了 SQLAlchemy 文档、Essential SQLAlchemy、stackoverflow 和几个源代码存储库,但一无所获。
u = self._table.update()
non_key_kw = {}
for column in self._table.c:
if column.name in self._table.primary_key:
u.where(self._table.c[column.name] == kw[column.name])
else:
col_name = column.name
non_key_kw[column.name] = kw[column.name]
print u
result = u.execute(kw)
哪个失败了 - 它似乎无法识别 where 子句:
UPDATE struct SET year=?, month=?, day=?, distance=?, speed=?, slope=?, temp=?
FAIL
而且我找不到任何以这种方式构建更新的示例。有什么建议吗?
I'm just using SQLAlchemy core, and cannot get the sql to allow me to add where clauses. I would like this very generic update code to work on all my tables. The intent is that this is part of a generic insert/update function that corresponds to every table. By doing it this way it allows for extremely brief test code and simple CLI utilities that can simply pass all args & options without the complexity of separate sub-commands for each table.
It'll take a few more tweaks to get it there, but should be doing the updates now just fine. However, while SQLAlchemy refers to generative queries it doesn't distinguish between selects & updates. I've reviewed SQLAlchemy documentation, Essential SQLAlchemy, stackoverflow, and several source code repositories, and have found nothing.
u = self._table.update()
non_key_kw = {}
for column in self._table.c:
if column.name in self._table.primary_key:
u.where(self._table.c[column.name] == kw[column.name])
else:
col_name = column.name
non_key_kw[column.name] = kw[column.name]
print u
result = u.execute(kw)
Which fails - it doesn't seem to recognize the where clause:
UPDATE struct SET year=?, month=?, day=?, distance=?, speed=?, slope=?, temp=?
FAIL
And I can't find any examples of building up an update in this way. Any recommendations?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
“where()”方法是生成性的,因为它返回一个新的
Update()
对象。旧的没有修改:the "where()" method is generative in that it returns a new
Update()
object. The old one is not modified: