Peter Kronenberg
Peter Kronenberg

Reputation: 1286

Alembic creates foreign key constraints before other table is created

I'm trying to setup Alembic for the first time. I dropped all my tables, so that Alembic would be starting from scratch. I entered

alembic revision --autogenerate -m "Initial tables"
alembic upgrade head

I got an immediate error because it was creating a table which has a foreign key. But the other table hadn't been created yet.

Here's an extract

def upgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table('calibration_metric',
    sa.Column('pk', sa.Integer(), nullable=False),
    sa.ForeignKeyConstraint(['metric_pk'], ['metric.pk'], ),
    sa.PrimaryKeyConstraint('pk')
    )

and then way down, many lines later

  op.create_table('metric',
  sa.Column('pk', sa.Integer(), nullable=False),

Is there a way to tell Alembic not to create the Foreign Key constraints until after all the tables have been created?

Any other solution?

Upvotes: 1

Views: 476

Answers (1)

Steven Cromb
Steven Cromb

Reputation: 61

# ### commands auto generated by Alembic - please adjust! ###

Alembic is recommending that you check and adjust the autogenerated files yourself.

You can move the create_table('metric',...) call above the create_table('calibration_metric',...) call so that the tables are created in a logical order.

Upvotes: 1

Related Questions