SQLAlchemy:将查询结果插入另一个表 [英] SQLAlchemy: Inserting the results of a query into another table

查看:326
本文介绍了SQLAlchemy:将查询结果插入另一个表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我从install表中得到了一些结果,像这样:

So I have some results which I've got from the install table, like so:

install = metadata.tables['install']  
results = session.query(install) #<sqlalchemy.orm.query.Query object>

我想将这些相同的结果插入到install_archive表中.

I'd like to insert these same results into the install_archive table.

我不确定如何执行此操作,因为我不想通过定义install-archive对象然后将结果解析为该对象来复制架构.我相信我没有使用ORM,因为我只是 reflecting (这是正确的说法吗?)表并对其进行查询.

I'm not entirely sure how to do this, because I don't want to duplicate the schema by defining an install-archive object and then parsing the results into that. I believe I'm not using the ORM, because I'm just reflecting (is that the right term?) the tables and querying them.

我可以看到的所有教程都使用ORM.

All the tutorials I can see use the ORM.

用伪代码执行此操作的慢速方法是:

A slow way of doing it, in psudocode, would be:

for id in result.all():
    install_archive.insert(install(id))

提前谢谢!

推荐答案

install_archive \
.insert() \
.from_select(names=['col1', 'col2'], # array of column names that your query returns
             select=session.query(install)) # your query or other select() object

这导致(PostgreSQL方言)

This results in (PostgreSQL dialect)

INSERT INTO install_archive (col1, col2)
SELECT install.col1, install.col2
FROM install;

这篇关于SQLAlchemy:将查询结果插入另一个表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆