Alembic autogenerate creates tables in wrong order with multi-tenant PostgreSQL schema

1 week ago 4
ARTICLE AD BOX

I have a FastAPI application with SQLAlchemy + Alembic managing a multi-tenant PostgreSQL database. My models use schema='per_tenant', and I translate this to actual tenant schemas (tenant_1, tenant_2, etc.) at migration runtime in env.py.

When I run alembic revision --autogenerate, the generated migration creates tables in the wrong order, causing foreign key constraint errors because dependent tables are created before their referenced tables.

Read Entire Article