【问题标题】:Updating models breaks past alembic migrations更新模型打破了过去的 Alembic 迁移
【发布时间】: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。如何让我的迁移再次运行?

【问题讨论】:

    标签: python sqlalchemy migration alembic


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2013-12-13
      • 2018-06-11
      • 2013-07-06
      • 2017-08-26
      • 2017-09-07
      • 2013-07-04
      • 1970-01-01
      • 2017-07-12
      相关资源
      最近更新 更多