Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLAlchemy: Inserting the results of a query into another table

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>

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

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.

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))

Thanks in advance!

like image 387
0atman Avatar asked Jun 18 '10 15:06

0atman


1 Answers

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

This results in (PostgreSQL dialect)

INSERT INTO install_archive (col1, col2)
SELECT install.col1, install.col2
FROM install;
like image 116
dtheodor Avatar answered Nov 09 '22 06:11

dtheodor