pythonintermediate

SQLModel CRUD Patterns

Use SQLModel (SQLAlchemy + Pydantic) to define models and run type-safe CRUD operations.

python
from sqlmodel import SQLModel, Field, Session, create_engine, select
from typing import Optional

class Hero(SQLModel, table=True):
    id:   Optional[int] = Field(default=None, primary_key=True)
    name: str
    age:  int

engine = create_engine('sqlite:///heroes.db')
SQLModel.metadata.create_all(engine)

with Session(engine) as session:
    session.add(Hero(name='Spider-Man', age=18))
    session.add(Hero(name='Iron Man',   age=45))
    session.commit()

with Session(engine) as session:
    heroes = session.exec(select(Hero).where(Hero.age > 20)).all()
    for h in heroes:
        print(h)

Use Cases

  • FastAPI backends
  • typed ORM
  • CRUD APIs

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.