Skip to main content

FastAPI for Django Developers

Software
Django makes a dozen choices before you write a line: one connection per request, lazy loading that just works, migrations that read your models, serializers that guard your columns. FastAPI with SQLAlchemy 2.0 and Alembic makes none of them. These are the seven that bit me, with the fix for each.
Author

Benedict Thekkel

Published

November 10, 2026

I have written Django for years (see Django Deep Cuts). This post comes from moving one small service in a side project from Django REST Framework to FastAPI, and from the two reference notebooks I wrote while doing it: FastAPI Stack and SQLAlchemy and Alembic. Those are the full reference. This is the opinionated short version.

The surprise was not that FastAPI is hard. It is small and pleasant. The surprise was how many decisions Django had been making on my behalf, silently and correctly, for years. FastAPI hands every one of them back. Each bug I hit lived in a decision I did not know I was now making.


The map

Most of Django has a direct counterpart. The rows that matter are the ones where the right-hand side is “you build it”.

Django / DRF FastAPI stack Who decides now
settings.py pydantic-settings Settings You, but it is typed
models.Model SQLAlchemy DeclarativeBase subclass You name the constraints
makemigrations / migrate alembic revision --autogenerate / alembic upgrade head You read every draft
ModelSerializer Pydantic models, one per shape You choose what leaves
ViewSet + DefaultRouter Functions on an APIRouter Same as before
request.user, permission_classes A CurrentUser dependency that raises 401/403 Same as before
Connection per request, ATOMIC_REQUESTS A session dependency you write You
select_related / prefetch_related joinedload / selectinload You, or it is an error
drf-spectacular Built in: /docs Nobody, it is free
Django admin Nothing built in (sqladmin is closest) You
Celery Celery, unchanged Same as before

The diagram shows one request through the new stack, with the six places (A to F) where a Django habit broke something.

One FastAPI request, the long-lived engine and Alembic, with six numbered traps

1. async def is a promise you have to keep

In Django every view runs in its own worker thread or process, so a slow call only blocks itself. In FastAPI the choice of keyword decides where your code runs.

You write FastAPI runs it Use it when
async def On the event loop, in the main thread Everything slow inside is awaited
def In a thread pool (40 threads by default) You call anything blocking

A blocking call inside async def stalls the event loop. While it waits, every other request in that process waits too. The bug does not show in a unit test. It shows as latency that climbs with load for no visible reason.

# wrong: requests.get blocks the event loop for every request in the process
@router.get("/rate")
async def rate():
    return requests.get(FX_URL).json()

# right: await an async client, or drop the async keyword and let it use a thread
@router.get("/rate")
async def rate(client: HttpDep):
    return (await client.get(FX_URL)).json()

My rule: write async def only when every slow call inside is awaited. Otherwise write def and let FastAPI find a thread. CPU-heavy work blocks either way, so it goes to anyio.to_thread.run_sync or to Celery.


2. Lazy loading is an error now

In Django, post.author quietly runs a query. At worst it is an N+1. In async SQLAlchemy the same attribute read raises MissingGreenlet, because a plain attribute access cannot await the IO it needs.

The fix is to say what you will touch as part of the query. The two loaders map straight onto what you already know:

SQLAlchemy SQL it runs Django nearest
joinedload(Post.author) LEFT OUTER JOIN in the same query select_related
selectinload(User.posts) A second SELECT ... WHERE id IN (...) prefetch_related
lazy="raise" Nothing. Access raises at once No equivalent
class User(Base):
    posts: Mapped[list["Post"]] = relationship(back_populates="author", lazy="raise")

stmt = select(User).options(selectinload(User.posts))
users = (await session.scalars(stmt)).all()

Put lazy="raise" on every relationship. Then a missing loader fails in your tests, with a message that names the attribute, instead of failing in production. I now think this is better than Django’s default. The N+1 that Django lets you ship by accident cannot be written at all.


3. The session is yours to scope

Django opens a connection per request and closes it after. With ATOMIC_REQUESTS it even wraps the request in a transaction. In FastAPI you write that scoping yourself, and there are two halves to get right.

The engine owns the connection pool. Create it once per process, at import. An engine per request is a pool per request. The session is one unit of work. Create one per request, through a dependency:

engine = create_async_engine(settings.database_url, pool_pre_ping=True)
SessionLocal = async_sessionmaker(engine, expire_on_commit=False)

async def get_session() -> AsyncIterator[AsyncSession]:
    async with SessionLocal() as session:
        yield session

SessionDep = Annotated[AsyncSession, Depends(get_session)]

Three details I missed at first:

  • expire_on_commit=False. The default expires every attribute on commit. In async code the next attribute read then needs IO, which is section 2 again.
  • Dependencies are cached per request. If the endpoint and get_current_user both ask for SessionDep, they share one session and one transaction. That is what you want.
  • A connection is checked out from the first query until the session commits or closes. A dependency that queries and then hands control to something that waits, keeps its connection the whole time. Under enough load, every pooled connection can be held by code that is waiting for something else. Commit, or close, as soon as a dependency has what it needs. (That one became a real deadlock under load testing. It gets its own post.)

4. Serializers became response models, and they are now the only guard

A DRF ModelSerializer with fields = [...] is an allow-list. You never think about it. In FastAPI, if you return an ORM object from an endpoint with no response_model, nothing stands between the row and the client. That includes password_hash.

Write one Pydantic model per direction and declare the output one on every endpoint:

class ItemCreate(BaseModel):
    title: str = Field(min_length=1, max_length=200)

class ItemRead(BaseModel):
    model_config = ConfigDict(from_attributes=True)
    id: int
    title: str

@router.post("/items", response_model=ItemRead, status_code=201)
async def create_item(body: ItemCreate, session: SessionDep, user: CurrentUser): ...

Error shapes change too. Pydantic and DRF word validation errors differently. A client that parses DRF’s {"title": ["This field may not be blank."]} gets a different body from FastAPI unless you add an exception handler that keeps the old shape. If anything outside your repo calls the API, decide that on day one.


5. Name your constraints before the first migration

Django names every index and constraint for you and remembers the names. SQLAlchemy without a naming convention lets PostgreSQL invent them, and then Alembic cannot refer to them in a later migration. Adding the convention later means a migration that renames every constraint you already have.

NAMING_CONVENTION = {
    "ix": "ix_%(column_0_label)s",
    "uq": "uq_%(table_name)s_%(column_0_name)s",
    "ck": "ck_%(table_name)s_%(constraint_name)s",
    "fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s",
    "pk": "pk_%(table_name)s",
}

class Base(DeclarativeBase):
    metadata = MetaData(naming_convention=NAMING_CONVENTION)

Two more things Django did silently: it indexes every foreign key, and SQLAlchemy does not (add index=True). And use DateTime(timezone=True) everywhere, then write datetime.now(UTC), never a naive datetime.


6. Autogenerate is a draft, not a migration

makemigrations asks you “did you rename this field?”. Alembic’s autogenerate does not ask. A renamed column comes out as drop the old column, add a new one, and the data goes with the drop. It runs cleanly and looks fine on an empty dev database.

Change What autogenerate writes What you write instead
Rename a column Drop plus add. Data lost op.alter_column(..., new_column_name=...)
Move or transform data Nothing op.execute(...) in its own revision
Add a PostgreSQL ENUM value Nothing ALTER TYPE ... ADD VALUE
Enable pgvector Nothing CREATE EXTENSION IF NOT EXISTS vector
A model module not imported in env.py Drops its table Import every model module in env.py

For data migrations the Django rule carries over, with less help. Django gives you apps.get_model() to get the historical model. Alembic has nothing, so describe the columns inline and never import your ORM models:

def upgrade() -> None:
    op.add_column("post", sa.Column("slug", sa.String(220), nullable=True))
    post = sa.table("post", sa.column("title", sa.String), sa.column("slug", sa.String))
    op.execute(post.update().values(slug=sa.func.lower(sa.func.replace(post.c.title, " ", "-"))))
    op.alter_column("post", "slug", nullable=False)

That is also the safe shape for a new required column on a table that has rows: add it nullable, fill it, then set NOT NULL. Read every generated revision before you apply it. That habit is the whole of Alembic safety.


7. Migrations are a deploy step, not a startup step

It is tempting to call alembic upgrade head in FastAPI’s lifespan, the way some Django images run migrate in the entrypoint. With more than one replica they start together and race the schema. Run the migration as its own step, before the new app containers start.

During a rolling deploy, old and new code run against the same schema for a while. So each migration must work with both versions. That is expand and contract: add the new column, deploy code that writes both, backfill, and drop the old column in a later release. A rename is three releases, not one.

One PostgreSQL detail: building an index locks writes on the table, and CREATE INDEX CONCURRENTLY cannot run inside a transaction. Alembic wraps each revision in one, so step outside it:

def upgrade() -> None:
    with op.get_context().autocommit_block():
        op.create_index("ix_post_title", "post", ["title"], postgresql_concurrently=True)

When I would still pick Django

Most of the time. Many CRUD models, a staff admin, one deployable unit: that is most business software, and Django does it with fewer decisions to get wrong. Its admin alone is worth weeks.

I pick FastAPI when the service is small and API-only, spends its time waiting on IO (streaming LLM output, proxying other APIs, WebSockets), or serves an ML model. Both sit happily behind the same React SPA, the same PostgreSQL and the same Celery, so it is a per-service choice, not a rewrite. The tooling around both is the same uv and ruff setup from The Modern Python Stack.

What makes the port safe is not the framework. It is a black-box test suite that runs the same HTTP requests against the old and the new service and compares the answers. With that in place, each of the decisions above becomes a test failure instead of a production surprise.


Takeaway

# Django did it for you In FastAPI + SQLAlchemy, do this
1 Every view had its own thread async def only if every slow call is awaited, else def
2 Lazy loading just worked lazy="raise" everywhere, joinedload / selectinload per query
3 Connection per request One engine per process, one session per request, expire_on_commit=False, release connections early
4 Serializer field allow-lists A response_model on every endpoint, one Pydantic model per direction
5 Named constraints, indexed foreign keys A naming convention on day one, index=True on foreign keys
6 makemigrations asked about renames Read every autogenerated revision; sa.table() in data migrations
7 migrate before start Migrate as a deploy step; expand and contract

FastAPI is not harder than Django. It is more honest about what a web service has to decide. Once you have made those seven decisions on purpose, the result is small, fast and easy to read, and every one of them is a line you can point at.

Full reference: FastAPI Stack and SQLAlchemy and Alembic.


Back to top