2015-09-08 35 views
6

我已经能够使用文档here中显示的相关更新构造来更新表中的一列。SQLAlchemy多个列的相关更新

例如:

sel = select([UpdateTable.column]).\ 
     where(UpdateTable.id == OrigTable.id) 

up = update(OrigTable).values(column=sel) 

将会产生像SQL:

UPDATE origtable SET column=(SELECT updatetable.column 
FROM updatetable 
WHERE updatetable.id = origtable.id) 

是否有可能使用Declaritive或查询API更新多个列的选择?

我试图仿效类似PostgreSQL中的以下内容:

UPDATE origtable 
    SET 
    column1 = updatetable.column1, 
    column2 = updatetable.column2 
    FROM updatetable 
    WHERE origtable.id == updatetable.id 

编辑:

看来,这个格式化单个语句可能无法与当前的SQLAlchemy API。

但是,使用here的解决方案似乎可以使用两个选择的解决方法。

+1

[该解决方案(http://stackoverflow.com/questions/30185056/updated-a-table-from-another-table-with-multiple-columns-in-sqlalchemy/30211905#30211905)并不是最优的,但可能已足够满足您的需求。 – lrnzcig

+0

谢谢@lrnzcig,我认为这可能是可能的。 我猜目前的API不直接支持这个。 – amckinley

+0

不客气。 (如果有帮助,我可以建议+1解决方案链接。谢谢。) – lrnzcig

回答

0

由于这是针对Postgresql的,我们可以使用SQLAlchemy的multiple table update支持。该文档是唯一的核心,但Query API之上构建的核心,我们可以apply that knowledge

session.query(OrigTable).\ 
    filter(OrigTable.id == UpdateTable.id).\ 
    update({OrigTable.column1: UpdateTable.column1, 
      OrigTable.column2: UpdateTable.column2}, 
      synchronize_session=False) 

导致

UPDATE origtable 
SET column1=updatetable.column1, 
    column2=updatetable.column2 
FROM updatetable 
WHERE origtable.id = updatetable.id