[Python] Alembic creates foreign key constraints before other table is created

Discussão em 'Python' iniciado por Stack, Julho 10, 2025.

  1. Stack

    Stack Membro Participativo

    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?

    Continue reading...

Compartilhe esta Página