SQLAlchemy 2.x introduced the Uuid mapped type and a cleaner Mapped annotation syntax for declarative models. UUID v7 integrates cleanly — the column default callable is invoked by SQLAlchemy’s unit-of-work before every INSERT, keeping generation at the application layer. See UUID in FastAPI for the full async route + dependency injection pattern.

Declarative model with UUID v7

# models.py
from sqlalchemy import String, text
from sqlalchemy.dialects.postgresql import UUID
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
import uuid

class Base(DeclarativeBase):
    pass

class Order(Base):
    __tablename__ = 'orders'

    id:          Mapped[uuid.UUID] = mapped_column(
        UUID(as_uuid=True),
        primary_key=True,
        default=uuid.uuid7,          # Python 3.13+ app-layer generation
        server_default=text('uuidv7()'),  # PostgreSQL 18 DB-layer fallback
    )
    customer_id: Mapped[uuid.UUID] = mapped_column(UUID(as_uuid=True), nullable=False)
    status:      Mapped[str]       = mapped_column(String(32), nullable=False)

default=uuid.uuid7 is a callable — SQLAlchemy calls it once per new object before INSERT. server_default is the database expression used when no Python value is provided (e.g., raw SQL inserts). See PostgreSQL 18 Ships Native UUID v7.

Async session — create and query

# db.py
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine, async_sessionmaker

engine       = create_async_engine('postgresql+asyncpg://user:pw@localhost/db')
AsyncSession = async_sessionmaker(engine, expire_on_commit=False)

# service.py
from .db import AsyncSession
from .models import Order
import uuid

async def create_order(customer_id: uuid.UUID, status: str) -> Order:
    async with AsyncSession() as session:
        order = Order(customer_id=customer_id, status=status)
        # id assigned by default=uuid.uuid7 before INSERT
        session.add(order)
        await session.commit()
        return order

async def get_order(order_id: uuid.UUID) -> Order | None:
    async with AsyncSession() as session:
        return await session.get(Order, order_id)

Alembic migration

# alembic/versions/xxxx_create_orders.py
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql

def upgrade():
    op.create_table(
        'orders',
        sa.Column('id',          postgresql.UUID(as_uuid=True), primary_key=True,
                  server_default=sa.text('uuidv7()')),  # PG 18+
        sa.Column('customer_id', postgresql.UUID(as_uuid=True), nullable=False),
        sa.Column('status',      sa.String(32),                 nullable=False),
        sa.Column('created_at',  sa.DateTime(timezone=True),
                  server_default=sa.text('now()'), nullable=False),
    )

def downgrade():
    op.drop_table('orders')

server_default=sa.text('uuidv7()') emits DEFAULT uuidv7() in the CREATE TABLE DDL — every INSERT path gets a UUID v7. See Zero-Downtime UUID Migration for adding this default to an existing table.

Time-range queries with UUID v7

from sqlalchemy import select
import uuid as uuid_mod

def build_uuid7_lower(ms: int) -> str:
    """Build the minimum UUID v7 for a given Unix millisecond timestamp."""
    hex_ts = format(ms, '012x')
    return f'{hex_ts[:8]}-{hex_ts[8:12]}-7000-8000-000000000000'

async def orders_last_hour(session: AsyncSession):
    lower = build_uuid7_lower(int(time.time() * 1000) - 3_600_000)
    result = await session.execute(
        select(Order)
        .where(Order.id >= uuid_mod.UUID(lower))
        .order_by(Order.id)
    )
    return result.scalars().all()

The primary key B-tree index serves this range query — no secondary created_at index is needed. See Time Precision for the 48-bit timestamp structure.

Python 3.9–3.12 — uuid6 backport

# requirements.txt
uuid6>=2022.12.0

# models.py
from uuid6 import uuid7
id = mapped_column(UUID(as_uuid=True), primary_key=True, default=uuid7)

See Python 3.13 uuid.uuid7() for the stdlib addition history.

Further reading

External references

Frequently asked questions

How do I use UUID v7 as a primary key in SQLAlchemy 2.x?

Use the Uuid type (SQLAlchemy 2.0+) or UUID(as_uuid=True) with default=uuid.uuid7 (Python 3.13) or default=uuid6.uuid7 (3.9–3.12). The callable is invoked by SQLAlchemy before each INSERT where id is not provided. For PostgreSQL 18, add server_default=text('uuidv7()') to also cover raw SQL inserts. See UUID in FastAPI for the FastAPI + async SQLAlchemy pattern.

Does Alembic support UUID v7 column defaults?

Alembic generates migration scripts from default=uuid.uuid7 as a Python-side default — the migration DDL will not include a database-level DEFAULT clause. To get a database-level default in Alembic, add server_default=text('uuidv7()') to the column; Alembic will emit DEFAULT uuidv7() in the generated migration. Requires PostgreSQL 18 or the pg_uuidv7 extension on earlier versions.