admin管理员组

文章数量:1202780

After the autogenrated initial migration, when running another autogeneration all foreign keys are beeing dropped and recreated.

Example Code from the migration script:

op.drop_constraint('fk_foo_bar_id_bar', 'foo', type_='foreignkey')
op.create_foreign_key(op.f('fk_foo_bar_id_bar'), 'foo', 'bar', ['bar_id'], ['id'], source_schema='public', referent_schema='public')

I tried changing env.py include_object as well as the way migrations were run. I also tried changing both foo and bar model in any way that seemed reasonable. Naming the FKs also didnt work.

After the autogenrated initial migration, when running another autogeneration all foreign keys are beeing dropped and recreated.

Example Code from the migration script:

op.drop_constraint('fk_foo_bar_id_bar', 'foo', type_='foreignkey')
op.create_foreign_key(op.f('fk_foo_bar_id_bar'), 'foo', 'bar', ['bar_id'], ['id'], source_schema='public', referent_schema='public')

I tried changing env.py include_object as well as the way migrations were run. I also tried changing both foo and bar model in any way that seemed reasonable. Naming the FKs also didnt work.

Share Improve this question asked Jan 21 at 3:49 tnfrutnfru 3541 silver badge11 bronze badges 1
  • Please edit the question to include a sample model that generates this behaviour, and the construction of the metadata object (for example, naming conventions). – snakecharmerb Commented Jan 21 at 10:48
Add a comment  | 

1 Answer 1

Reset to default 0

The solution lies in removing the explicit definition of the public schema in your classes.

So if you have this in your bar class

bar_id: Mapped[Integer] = mapped_column(
        ForeignKey("public.bar.id"), index=True, type_=Integer
    )

And in your foo class

__table_args__ = (
    {"schema": "public"},
)

Remove both public statements. Postgres does sometimes not explicitly name it that way and alembic then thinks it is a different FK and tries to recreate them.

本文标签: pythonAlembic keeps deleting and recreating Foreign Keys during autogenrationStack Overflow