简体   繁体   中英

SQLAlchemy - How can I copy rows from one table to another?

Let's say I have the following tables with the columns in parens:

  • fruits (id, name, weight)

  • apples (fruit_id, name, type)

I'm trying to copy only the data in the id and name columns from fruits into apples .

So far I have:

fruit_rows = Fruits.query.all()

for fruit_row in fruit_rows:
    apple_row = Apples(
        fruit_id=Fruits.id,
        name=Fruits.name,
    )
    session.merge(apple_row)


session.commit()

Am I on the right track here?

fruit_rows = Fruits.query.all()

for fruit_row in fruit_rows:
    apple_row = Apples(
        fruit_id=fruit_row.id,
        name=fruit_row.name,
    )
    session.add(apple_row)


session.commit()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM