/py-pit:sqlalchemy-modelsfrom py-pit
Creates production-ready SQLAlchemy 2.x ORM models with typed columns, relationships, DeclarativeBase, mixins, and clean package structure for Python/FastAPI backends.
Ships in py-pit. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
This skill creates clean, production-ready SQLAlchemy 2.x ORM models for Python backend projects.
It enforces disciplined model patterns that prevent common problems such as:
The skill favors explicit, typed, migration-friendly ORM design and ensures model code is:
Produce a model layer that:
Before generating anything:
models/ package or existing model files already exist. If
they do, extend the existing structure rather than creating a parallel one.fastapi-init, the package root is {pkg_name}/{pkg_name}/ — place models
at {pkg_name}/models/, not app/models/.DeclarativeBase subclass already exists anywhere. If one
does, adopt it rather than introducing a second base.env.py is present and how it imports
Base.metadata — preserve that import path.Use this skill when the user:
Do not use this skill when:
This skill does not:
When applying this skill:
Prefer a single canonical base in db/base.py, separate from the engine and session factory. Include a naming convention so Alembic generates predictable constraint names:
from sqlalchemy import MetaData
from sqlalchemy.orm import DeclarativeBase
convention = {
"ix": "ix_%(column_0_label)s",
"uq": "uq_%(table_name)s_%(column_0_name)s",
"ck": "ck_%(table_name)s_%(constraint_name)s",
"fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s",
"pk": "pk_%(table_name)s",
}
class Base(DeclarativeBase):
metadata = MetaData(naming_convention=convention)
Model files import Base from db/base.py:
from {pkg_name}.db.base import Base
Do not create multiple unrelated declarative bases unless the repo already intentionally uses them.
Prefer:
from sqlalchemy import String
from sqlalchemy.orm import Mapped, mapped_column
email: Mapped[str] = mapped_column(String(255), unique=True, index=True)
Avoid legacy untyped declarations like:
email = Column(String, unique=True)
unless the repo is explicitly locked to an older SQLAlchemy style and the user did not ask for modernization.
Default to a simple explicit primary key:
id: Mapped[int] = mapped_column(primary_key=True)
Only introduce UUIDs or custom identifiers when the repo already uses them or there is a clear requirement.
Prefer fully paired relationships:
class User(Base):
__tablename__ = "users"
id: Mapped[int] = mapped_column(primary_key=True)
posts: Mapped[list["Post"]] = relationship(back_populates="author")
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")
Avoid one-sided relationships unless intentionally required.
Prefer string references in relationships when models live in separate files:
posts: Mapped[list["Post"]] = relationship(back_populates="author")
This helps avoid circular imports and keeps modules loosely coupled.
Be deliberate about nullability, uniqueness, indexes, and defaults.
Prefer model fields that make schema intent obvious.
Do not rely on vague or accidental defaults.
Use mixins only where they reduce obvious duplication.
Typical good candidates:
Example:
from datetime import datetime, timezone
from sqlalchemy import DateTime
from sqlalchemy.orm import Mapped, mapped_column
def utcnow() -> datetime:
return datetime.now(timezone.utc)
class TimestampMixin:
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow)
updated_at: Mapped[datetime] = mapped_column(
DateTime(timezone=True),
default=utcnow,
onupdate=utcnow,
)
Do not add mixins that obscure the real model shape.
Prefer a predictable model package. Adapt the root to the actual project layout
found in Step 0 — for fastapi-init projects this is {pkg_name}/models/, for
other layouts it may be app/models/ or similar.
{pkg_name}/
db/
base.py # Base, TimestampMixin, naming convention
session.py # engine, AsyncSessionLocal, get_db
models/
__init__.py
user.py
post.py
Where appropriate:
Base and shared mixins live in db/base.py (separate from engine and session)models/models/__init__.py should import all model classes so that
Base.metadata is fully populated when Alembic (or any other tool)
imports it — this is what makes autogenerate reliableAvoid dumping all models into one huge file once the project has more than a few entities.
Prefer explicit imports.
Good:
from {pkg_name}.db.base import Base
from {pkg_name}.models.user import User
from {pkg_name}.models.post import Post
Avoid wildcard imports:
from {pkg_name}.models import *
Also avoid tangled cross-import chains between model modules.
Keep ORM models and Pydantic schemas separate.
ORM models represent:
Pydantic schemas represent:
Do not collapse both concerns into the same class structure.
Model code should be written so Alembic autogenerate can reason about it cleanly.
Prefer:
Avoid patterns that obscure metadata registration or hide model definitions.
This skill does not redesign session management unless necessary, but it should produce model code that fits normal FastAPI backend usage.
Assume the expected separation is:
models/Before finishing, verify:
BaseMapped[...] and mapped_column(...)__tablename__ is defined consistentlyColumn(...) style mixed inconsistently with 2.x styleback_populatesWhen using this skill, the assistant should usually:
This skill pairs naturally with others in this plugin and anticipated future skills. Not all of these exist yet — treat them as integration points, not dependencies.
settings-config — database URL and other config values come from herepydantic-schemas — API request/response schemas that mirror (but stay
separate from) the ORM modelsalembic-migrations — migration authoring from model metadatapytest-service — test fixtures that use SQLite in-memory DBA route/service layer skill is planned - check the plugin's current skill list for availability.
Typical order when building from scratch:
settings-configsqlalchemy-modelspydantic-schemasalembic-migrationsWhat SKILL.md sets; muted values are Claude Code's defaults
Generated from the plugin's indexed repository (robhowley/py-pit-skills) — no native marketplace selected
npx claudepluginhub p/robhowley-py-pit16 skills in this plugin
/alembic-migrationsProduction-safe Alembic migration workflows for SQLAlchemy 2.x projects. Use this skill when adding Alembic, generating migrations, reviewing autogenerate diffs, fixing broken migrations, or establishing a safe schema evolution workflow in a Python backend./background-jobs-boundariesGuardrails for background work in FastAPI and Python services. Prevent misuse of in-process background execution (e.g. FastAPI BackgroundTasks)./click-cliDesign, generate, and improve Python CLIs using the Click library. Focus on idiomatic architecture, command groups, modular layouts, CLI UX conventions, and avoiding common Click anti-patterns./click-cli-linterAudit and improve existing Python Click CLIs by identifying architecture problems, anti-patterns, and CLI UX issues, then proposing minimal, high-value fixes./code-qualityOpinionated code health stack for Python repos using Ruff, pre-commit, and Markdown linting. Prefers consolidation over redundant tooling, preserves working repos unless migration is requested, and provides a simple adoption path for both new and existing projects./dockerize-serviceGenerate a local-development Docker Compose setup for an existing Python project. Produces a multi-stage Dockerfile, Compose file, env config, and dockerignore based on detected project signals.Other plugins' skills for the same job