0

I have a series of alembic migrations similar to the following

# 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'])

Since I added the third migration, if I re-run all my migrations from the beginning I get an error because when it tries to run migration #2 it tries to insert the my_other_model_id into the my_model table, but the column won't exist until after migration #3 has run.

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...

I can't see how to exclude the my_model_id from the insert in the second migration. How can I get my migrations running again?

Jim Jeffries
  • 9,841
  • 15
  • 62
  • 103

1 Answers1

0

I've found a workaround for this by changing migration #2 to use an insert statement instead

insert(MyModel).values(id=1, text='text')
Jim Jeffries
  • 9,841
  • 15
  • 62
  • 103