【发布时间】:2017-08-26 11:21:12
【问题描述】:
假设我的数据库模型包含一个对象User:
Base = declarative_base()
class User(Base):
__tablename__ = 'users'
id = Column(String(32), primary_key=True, default=...)
name = Column(Unicode(100))
我的数据库包含一个带有 n 行的 users 表。在某些时候,我决定将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 解决方案。 This one 和 this one 都建议使用 execute() 和 bulk_insert() 在迁移期间执行原始 SQL 语句。 This (incomplete) solution 导入当前的数据库模型,但是当模型发生变化时,这种方法很脆弱。
如何在 Alembic 迁移期间迁移和修改列数据的现有内容?推荐的方法是什么,它记录在哪里?
【问题讨论】:
标签: python-3.x alembic sqlalchemy-migrate