Search code examples
pythonpeewee

How should I move a record between tables using Peewee?


I have two tables with identical fields. One is for active users and one is for archived users:

 class BaseClass(Model)
      class Meta:
           database = db

 class User(BaseClass):
      name = CharField()
      # Various other fields

 class UserArchive(BaseClass):
      name = CharField()
      # Identical fields to User

Users are added like this:

 User.create(name = "Tim")

But when I need to move a user from User to UserArchive, I do something like this:

 user = User.get(User.name == "Tim")
 user_data = user._data
 del user_data["id"]
 UserArchive.create(**user_data)
 user.delete_instance()

This feels a bit cumbersome. Is there a recommended way to move a record from one table to another?


Solution

  • UserArchive.insert_from(
       query=User.select(User.name).where(User.active == False),
       columns=[UserArchive.name])
    

    Generates

    INSERT INTO userarchive ("name") SELECT "name" FROM user WHERE "active" = false;
    

    Provide your own where clause to suit your needs. You'll still need to delete the User row of course.