假设我的数据库模型包含一个对象User
:
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
id = Column(String(32), primary_key=True, default=...)
name = Column(Unicode(100))
我的数据库包含一个有n行的users
表。在某些时候,我决定将其拆分为and ,并且在此期间我希望我的数据也能被迁移。name
firstname
lastname
alembic upgrade head
自动生成的Alembic迁移如下:
def upgrade():
op.add_column('users', sa.Column('lastname', sa.Unicode(length=50), nullable=True))
op.add_column('users', sa.Column('firstname', sa.Unicode(length=50), nullable=True))
# Assuming that the two new columns have been committed and exist at
# this point, I would like to iterate over all rows of the name column,
# split the string, write it into the new firstname and lastname rows,
# and once that has completed, continue to delete the name column.
op.drop_column('users', 'name')
def downgrade():
op.add_column('users', sa.Column('name', sa.Unicode(length=100), nullable=True))
# Do the reverse of the above.
op.drop_column('users', 'firstname')
op.drop_column('users', 'lastname')
这个问题似乎有多种或多或少的hacky解决方案。这个和这个都建议在迁移期间使用execute()
和bulk_insert()
执行原始 SQL 语句。这个(不完整的)解决方案导入了当前的数据库模型,但是当模型发生变化时,这种方法很脆弱。
如何在 Alembic 迁移期间迁移和修改列数据的现有内容?推荐的方法是什么,它记录在哪里?