Search code examples
pythonmysqlpython-2.7ormpeewee

How can I replace the whole table's content with another table's content


I need to replace the whole content of one table with another table's content. Both tables have the same fields.

I don't see any way to execute ALTER TABLE statement via Peewee, so I decided to use the combination of DROP TABLE, CREATE TABLE and INSERT ... FROM statements like this:

TableInWhichIWantToReplaceAllData.drop_table()
db.create_table(TableInWhichIWantToReplaceAllData)
TableWithNewData.insert_from(
    # ???,
    # ???
).execute()

But the problem is how can I specify all fields to be SELECTed and INSERTed? I don't want to manually specify all of them like in example:

source = (User
          .select(User.username, fn.COUNT(Tweet.id))
          .join(Tweet, JOIN.LEFT_OUTER)
          .group_by(User.username))
UserTweetDenorm.insert_from(
    [UserTweetDenorm.username, UserTweetDenorm.num_tweets],
    source).execute()

Is there any other way?


Solution

  • Peewee supports table changes via the migrations extension. Specifically it sounds like you want to rename a table.

    Alternatively, you can use the INSERT INTO ... SELECT FROM as you have. To get all the fields on a model, you can use ModelClass._meta.sorted_fields (2.7.0 and newer) or ModelClass._meta.get_fields() (2.6.4 and older).

       select = TableWithData.select()
       insert = NewTable.insert_from(NewTable._meta.get_fields(), select)
    

    I believe that should do the trick, but honestly...just use the migrator.