Set up SQLAlchemy ORM with models and migrations (Alembic)
✓Works with OpenClaudeYou are a Python backend developer. The user wants to set up SQLAlchemy ORM with declarative models and configure Alembic for database migrations.
What to check first
- Run
pip list | grep -i sqlalchemyto verify SQLAlchemy is installed (need version 2.0+) - Run
pip list | grep -i alembicto confirm Alembic is available - Check if a
migrations/directory already exists in your project root
Steps
- Install SQLAlchemy and Alembic:
pip install sqlalchemy alembic psycopg2-binary(psycopg2 for PostgreSQL; usepymysqlfor MySQL) - Create a
database.pyfile withcreate_engine()andsessionmaker()to establish the database connection - Create a
models.pyfile and importdeclarative_basefromsqlalchemy.ormto define your base class - Define model classes inheriting from
Basewith__tablename__and Column definitions usingInteger,String,DateTime, etc. - Initialize Alembic in your project:
alembic init migrationsto generate thealembic.iniandmigrations/directory - Edit
migrations/env.pyto import yourBasemetadata and settarget_metadata = Base.metadata - Update the
sqlalchemy.urlinalembic.iniwith your database connection string (e.g.,postgresql://user:pass@localhost/dbname) - Generate the first migration:
alembic revision --autogenerate -m "Initial schema"to detect model changes - Apply migrations:
alembic upgrade headto create tables in the database
Code
# database.py
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, Session
DATABASE_URL = "postgresql://user:password@localhost/mydb"
engine = create_engine(DATABASE_URL, echo=True)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
# models.py
from sqlalchemy import Column, Integer, String, DateTime, Boolean, ForeignKey
from sqlalchemy.orm import declarative_base, relationship
from datetime import datetime
Base = declarative_base()
class User(Base):
__tablename__ = "users"
id = Column(Integer, primary_key=True, index=True)
email = Column(String(255), unique=True, nullable=False, index=True)
username = Column(String(100), nullable=False)
hashed_password = Column(String(255), nullable=False)
is_active = Column(Boolean, default=True)
created_at = Column(DateTime, default=datetime.utcnow)
posts = relationship
Note: this example was truncated in the source. See the GitHub repo for the latest full version.
Common Pitfalls
- Treating this skill as a one-shot solution — most workflows need iteration and verification
- Skipping the verification steps — you don't know it worked until you measure
- Applying this skill without understanding the underlying problem — read the related docs first
When NOT to Use This Skill
- When a simpler manual approach would take less than 10 minutes
- On critical production systems without testing in staging first
- When you don't have permission or authorization to make these changes
How to Verify It Worked
- Run the verification steps documented above
- Compare the output against your expected baseline
- Check logs for any warnings or errors — silent failures are the worst kind
Production Considerations
- Test in staging before deploying to production
- Have a rollback plan — every change should be reversible
- Monitor the affected systems for at least 24 hours after the change
Related Python Skills
Other Claude Code skills in the same category — free to download.
Django Setup
Scaffold Django project with models, views, and URLs
Flask Setup
Scaffold Flask application with blueprints and extensions
FastAPI Setup
Scaffold FastAPI with async endpoints and auto-docs
Pytest Setup
Configure pytest with fixtures, plugins, and coverage
Python Venv
Set up Python virtual environments and dependency management
Poetry Setup
Set up Poetry for Python dependency and package management
Python Typing
Add comprehensive type hints and mypy configuration to Python code
Django REST Framework
Set up Django REST Framework with serializers and viewsets
Want a Python skill personalized to YOUR project?
This is a generic skill that works for everyone. Our AI can generate one tailored to your exact tech stack, naming conventions, folder structure, and coding patterns — with 3x more detail.