Skip to content

SQLAlchemy 2.0: Modern ORM Patterns for Python

By TechLog Admin 1 min read

SQLAlchemy 2.0: Modern ORM Patterns

SQLAlchemy 2.0 introduces a unified API that combines the best of ORM and Core. Here's what changed.

The New Way

Declarative Models with Type Annotations

from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column

class Base(DeclarativeBase):
    pass

class User(Base):
    __tablename__ = "users"

    id: Mapped[int] = mapped_column(primary_key=True)
    name: Mapped[str] = mapped_column(String(100))
    email: Mapped[str] = mapped_column(String(255), unique=True)

Async Sessions

from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession

engine = create_async_engine("postgresql+asyncpg://user:pass@localhost/db")

async with AsyncSession(engine) as session:
    result = await session.execute(select(User))
    users = result.scalars().all()

Key Changes from 1.x

  • Session.execute() is now the primary query interface
  • select() replaces Query API
  • Mapped[] replaces Column annotations
  • Native async support without hacks

Relationship Patterns

class Post(Base):
    __tablename__ = "posts"

    id: Mapped[int] = mapped_column(primary_key=True)
    author_id: Mapped[int] = mapped_column(ForeignKey("users.id"))
    author: Mapped[User] = relationship(back_populates="posts")
SQLAlchemy 2.0 represents a mature, well-designed ORM that embraces modern Python features.

This article is also available in:

Comments

Loading comments...

Related Articles