SQLAlchemy: insert query results into another table

So, I have some results that I got from the install table, for example:

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

I would like to insert the same results into the install_archive table.

I am not quite sure how to do this because I do not want to duplicate the schema by defining an install-archive object and then analyzing the results. I believe that I do not use ORM because I am just thinking (is this the right term?) The tables and requests them.

All the tutorials that I see use ORM.

The slow way to do this, in psudocode, would be:

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

Thanks in advance!

+7
python sql mysql sqlalchemy
source share
2 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 

Result (PostgreSQL dialogs)

 INSERT INTO install_archive (col1, col2) SELECT install.col1, install.col2 FROM install; 
+5
source share

You can do something like this (changing SELECT to suit your needs). Just make sure the two tables have the same structure.

 INSERT INTO `table1` (SELECT * FROM `table2`); 
0
source share

All Articles