python:sqlalchemy
SQLAlchemy ORM Patterns
Modern SQLAlchemy 2.0+ patterns for database access in Python applications.
Model Definition
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column
from sqlalchemy import String
from uuid import UUID
from decimal import Decimal
class Base(DeclarativeBase):
pass
class ProductModel(Base):
__tablename__ = "products"
id: Mapped[UUID] = mapped_column(primary_key=True)
name: Mapped[str] = mapped_column(String(100))
price: Mapped[Decimal]
in_stock: Mapped[bool] = mapped_column(default=True)
Session Management
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
engine = create_engine("postgresql://user:pass@localhost/db")
SessionLocal = sessionmaker(bind=engine)
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
Query Patterns
# Select
stmt = select(ProductModel).where(ProductModel.price > 100)
products = session.execute(stmt).scalars().all()
# Filter
products = session.query(ProductModel).filter(ProductModel.in_stock == True).all()
# Get by ID
product = session.get(ProductModel, product_id)
# Count
count = session.query(ProductModel).count()
Upsert
from sqlalchemy.dialects.postgresql import insert
stmt = insert(ProductModel).values(
id=product_id,
name="Widget",
price=9.99,
)
# On conflict, update
stmt = stmt.on_conflict_do_update(
index_elements=["id"],
set_={"name": stmt.excluded.name, "price": stmt.excluded.price},
)
session.execute(stmt)
session.commit()
Relationships
from sqlalchemy.orm import relationship
class UserModel(Base):
__tablename__ = "users"
id: Mapped[int] = mapped_column(primary_key=True)
orders: Mapped[list["OrderModel"]] = relationship(back_populates="user")
class OrderModel(Base):
__tablename__ = "orders"
id: Mapped[int] = mapped_column(primary_key=True)
user_id: Mapped[int] = mapped_column(ForeignKey("users.id"))
user: Mapped["UserModel"] = relationship(back_populates="orders")
JSON Columns
from sqlalchemy import JSON
class ConfigModel(Base):
__tablename__ = "configs"
id: Mapped[int] = mapped_column(primary_key=True)
settings: Mapped[dict] = mapped_column(JSON)
# Query JSON field
configs = session.query(ConfigModel).filter(
ConfigModel.settings["theme"] == "dark"
).all()
See references/ for model patterns, query optimization, and async SQLAlchemy.
More from martinffx/claude-code-atelier
python:architecture
Python application architecture with functional core, effectful shell, DDD, and data modeling. Use when designing application layers, separating pure business logic from IO, defining domain models, implementing validation, or structuring bounded contexts.
14python:monorepo
Python monorepo architecture with uv workspaces, mise, and apps/packages pattern. Use when setting up project structure, configuring workspaces, managing dependencies across packages, or designing multi-app Python repositories.
13python:build-tools
Python project tooling with uv, mise, ruff, basedpyright, and pytest. Use when setting up pyproject.toml, running builds, typechecking, configuring tests, linting, formatting, or managing Python environments.
12python:modern-python
Modern Python language features and typing patterns. Use when writing type hints, using generics, implementing pattern matching, working with async/await, or leveraging Python 3.10+ features.
12python:testing
Stub-Driven TDD and layer boundary testing with pytest. Use when writing tests, deciding what to test, testing at component boundaries, or implementing test-driven development.
12python:fastapi
Building REST APIs with FastAPI, Pydantic validation, and OpenAPI. Use when creating routes, handling requests, designing endpoints, implementing validation, error responses, pagination, or generating API documentation.
11