更新模型打破了过去的 Alembic 迁移

Posted

技术标签:

【中文标题】更新模型打破了过去的 Alembic 迁移【英文标题】:Updating models breaks past alembic migrations 【发布时间】:2021-12-17 22:26:11 【问题描述】:

我有一系列类似于以下的 alembic 迁移

# 1
def upgrade():
    op.create_table('my_model',
    sa.Column('id', sa.Integer(), nullable=False),
    sa.Column('text', sa.Text())
    )


# 2
def upgrade():
    my_model = MyModel(id=1, text='text')
    session.add(my_model)
    session.commit()

# 3
def upgrade():
    op.create_table('my_other_model',
        sa.Column('id', sa.Integer(), nullable=False)
    )
    op.add_column('my_model', sa.Column('my_other_model_id', sa.Integer(), nullable=True))
    op.create_foreign_key('my_model_my_other_model_id_fkey', 'my_model', 'my_other_model', ['my_other_model_id'], ['id'])

由于我添加了第三个迁移,如果我从头开始重新运行所有迁移,我会收到一个错误,因为当它尝试运行迁移 #2 时,它会尝试将 my_other_model_id 插入到 my_model 表中,但是在迁移 #3 运行之后,该列才会存在。

sqlalchemy.exc.ProgrammingError: (psycopg2.errors.UndefinedColumn) column "my_other_model_id" of relation "my_model" does not exist
LINE 1: ..._model (id, text, my_other_model...

我看不到如何在第二次迁移中从插入中排除 my_model_id。如何让我的迁移再次运行?

【问题讨论】:

【参考方案1】:

我通过将迁移 #2 更改为使用插入语句找到了解决方法

insert(MyModel).values(id=1, text='text')

【讨论】:

以上是关于更新模型打破了过去的 Alembic 迁移的主要内容,如果未能解决你的问题,请参考以下文章

4.alembic数据迁移工具

使用alembic进行数据库版本管理

使用alembic进行数据库版本管理

使用 sqlmodel 的 alembic 迁移尝试更改主键列

flask数据库之alembic的使用

Six——tornado操作之用户表单(密码,用户名)数据库迁移使用SQLAlchemy+pymysql配合alembic实现!