Inspired by creating a temporary table from a query using sqlalchemy orm I had similar requirement but only needs PrimaryKey Constraint and want to add ForeinKeyConstraint based on new temp tables created.
I have added only foreign constraint by checking if the constraint is of type PrimaryKeyConstraint
then add in constraints
constraints = [c.copy() for c in table.constraints if isinstance(c,PrimaryKeyConstraint)]
This is fine but I want to create a foreign key constraint on two newly created tables. I have tried
constraints.append(ForeignKeyConstraint(['id'],['schema2.temp_table1.id']))
and as suggested added back to the table
temp_table = Table(name, metadata, *(cols + constraints), schema=schema)
But it is taking a long time to create and insert the data. Any suggestions would be helpful.