SQLAlchemy 2.x overhauled its type system and ORM mapping layer, and UUID handling benefited directly. The new Uuid type, the mapped_column() API, and Python 3.13’s uuid.uuid7() standard library addition combine to make UUID v7 primary keys concise and fully typed in modern Python applications. This article covers the patterns for both application-layer and server-side UUID v7 generation, migration from legacy String-based UUID columns, and Alembic integration.

The Uuid column type

SQLAlchemy 2 ships sqlalchemy.Uuid as a database-agnostic UUID column type. It stores and retrieves uuid.UUID Python objects directly — no manual string conversion required:

from uuid import UUID, uuid4
from sqlalchemy import Uuid
from sqlalchemy.orm import DeclarativeBase, mapped_column, Mapped

class Base(DeclarativeBase):
    pass

class User(Base):
    __tablename__ = "users"

    id: Mapped[UUID] = mapped_column(Uuid, primary_key=True, default=uuid4)
    email: Mapped[str] = mapped_column(unique=True)

The Mapped[UUID] annotation tells mypy and Pyright that user.id is a uuid.UUID instance, not a string. This eliminates an entire class of bugs where UUID values were compared as strings with inconsistent casing.

Switching the default to UUID v7

Replacing uuid4 with uuid.uuid7 (Python 3.13+) is a single-character change:

import uuid
from sqlalchemy import Uuid
from sqlalchemy.orm import DeclarativeBase, mapped_column, Mapped

class Base(DeclarativeBase):
    pass

class Event(Base):
    __tablename__ = "events"

    id: Mapped[uuid.UUID] = mapped_column(
        Uuid,
        primary_key=True,
        default=uuid.uuid7,   # Python 3.13+
    )
    payload: Mapped[str]
    created_at: Mapped[str]

For Python 3.9–3.12, install the uuid6 backport and substitute uuid6.uuid7:

import uuid6

id: Mapped[uuid6.UUID] = mapped_column(
    Uuid,
    primary_key=True,
    default=uuid6.uuid7,
)

The default callable is invoked by SQLAlchemy at insert time — before the SQL is sent to the database. This means the UUID v7 value is available in the Python object immediately after session.add(obj), without needing to flush or refresh.

Using server_default on PostgreSQL 18

For teams on PostgreSQL 18, delegating UUID generation to the database via server_default is cleaner because it ensures every insert path — ORM, raw SQL, migration scripts — generates a consistent UUID v7:

from sqlalchemy import Uuid, text
from sqlalchemy.orm import DeclarativeBase, mapped_column, Mapped
import uuid

class Base(DeclarativeBase):
    pass

class Order(Base):
    __tablename__ = "orders"

    id: Mapped[uuid.UUID] = mapped_column(
        Uuid,
        primary_key=True,
        server_default=text("uuidv7()"),
    )
    total_cents: Mapped[int]

server_default=text("uuidv7()") maps to a SQL DEFAULT uuidv7() expression in the DDL. SQLAlchemy retrieves the generated value via RETURNING id after insert. The Python id attribute is populated automatically — no .refresh() needed.

On PostgreSQL 17 and earlier, replace uuidv7() with gen_uuid_v7() from the pg_uuidv7 extension, or switch to the application-layer default=uuid.uuid7 approach.

Comparing application-layer vs server-side generation

ApproachPostgreSQL versionUUID available before flush?Works with raw SQL inserts?
default=uuid.uuid7AnyYesNo — only through ORM
server_default=text("uuidv7()")18+ (or with pg_uuidv7)No (needs flush)Yes
server_default=text("gen_random_uuid()")13+ built-inNo (needs flush)Yes, but generates v4

For most web applications where all writes go through SQLAlchemy, application-layer generation with default=uuid.uuid7 is the simplest choice. For data pipelines, migration scripts, or multi-ORM architectures, server_default is safer.

Alembic migration for an existing VARCHAR column

If you have existing tables using String(36) or String(32) to store UUIDs as text, you can migrate to the Uuid type with an Alembic revision:

# alembic/versions/20261020_uuid_v7_migration.py
from alembic import op
import sqlalchemy as sa

def upgrade():
    # For PostgreSQL — cast the existing text to uuid
    op.alter_column(
        "users",
        "id",
        existing_type=sa.String(36),
        type_=sa.Uuid(),
        postgresql_using="id::uuid",
    )
    op.execute("ALTER TABLE users ALTER COLUMN id SET DEFAULT uuidv7()")

def downgrade():
    op.execute("ALTER TABLE users ALTER COLUMN id DROP DEFAULT")
    op.alter_column(
        "users",
        "id",
        existing_type=sa.Uuid(),
        type_=sa.String(36),
        postgresql_using="id::text",
    )

The postgresql_using parameter is required when the column contains data — PostgreSQL needs an explicit cast expression to know how to convert each existing value. Existing UUID v4 strings are valid UUIDs and cast cleanly; mixed-case strings must be lowercased first if your application ever stored uppercase UUIDs.

Async SQLAlchemy with UUID v7

The pattern is identical for AsyncSession:

from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
from sqlalchemy.orm import sessionmaker
import uuid

engine = create_async_engine("postgresql+asyncpg://user:pass@localhost/db")
AsyncSessionLocal = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)

async def create_user(email: str) -> User:
    async with AsyncSessionLocal() as session:
        user = User(email=email)  # id is set by default=uuid.uuid7 at instantiation
        session.add(user)
        await session.commit()
        return user  # user.id is already populated

Because the default=uuid.uuid7 callable runs in Python before any SQL is executed, the UUID is populated synchronously at object creation — no async call required to get the ID.

Further reading

External references

Frequently asked questions

Does SQLAlchemy 2.x store UUIDs as native uuid or as VARCHAR?

It depends on the database. For PostgreSQL, the Uuid type maps to the native uuid column type. For databases without a native uuid type (SQLite, MySQL pre-8.0), SQLAlchemy stores the UUID as CHAR(32) or VARCHAR(36) depending on the native_uuid flag on the type.

Can I use SQLAlchemy UUID v7 with FastAPI?

Yes. Use Python's uuid.UUID type as the Pydantic model field and mapped_column(Uuid, primary_key=True, default=uuid.uuid7) in the SQLAlchemy model. FastAPI serialises uuid.UUID to a lowercase hyphenated string automatically. See UUID in Python for a complete FastAPI + SQLAlchemy example.

What Python version is required for uuid.uuid7()?

Python 3.13 added uuid.uuid7() to the standard library. For Python 3.9–3.12, use the uuid6 backport on PyPI and call uuid6.uuid7() instead. The SQLAlchemy column default accepts either callable.

Does server_default work with Alembic autogenerate?

Yes. When you set server_default=text("uuidv7()") on a column, Alembic's autogenerate will include the server default in the generated migration. Ensure you are on PostgreSQL 18+ where uuidv7() is a built-in function, or have the pg_uuidv7 extension installed on earlier versions.