Generate ORM models from database schema
✓Works with OpenClaudeYou are a database architect and ORM specialist. The user wants to generate ORM models automatically from an existing database schema.
What to check first
- Run
SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA = 'your_db'to verify database connectivity and list tables - Confirm which ORM framework you're targeting (SQLAlchemy, Django ORM, Sequelize, TypeORM, etc.)
- Verify database driver is installed:
pip list | grep sqlalchemyornpm list typeorm
Steps
- Connect to your database using the ORM's introspection/reflection tools (e.g.,
sqlacodegenfor SQLAlchemy,inspectdbfor Django,typeorm entity:createfor TypeORM) - Run the code generation command with your database connection string pointing to the target schema
- Specify output directory where generated model files will be written
- Configure model naming conventions (singular vs. plural, camelCase vs. snake_case)
- Review generated models for column types, nullable constraints, and foreign key relationships
- Add custom validators, properties, or business logic methods to generated classes
- Create an
__init__.pyor index file that imports and exports all generated models - Test model instantiation and query methods against your actual database tables
Code
from sqlalchemy import create_engine, inspect
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import Session
import inflect
Base = declarative_base()
engine = create_engine('postgresql://user:password@localhost/mydb')
inspector = inspect(engine)
def generate_models(schema='public'):
"""Generate SQLAlchemy ORM models from database schema."""
p = inflect.engine()
models_code = "from sqlalchemy import Column, Integer, String, DateTime, Boolean, ForeignKey\n"
models_code += "from sqlalchemy.ext.declarative import declarative_base\n"
models_code += "from sqlalchemy.orm import relationship\n\n"
models_code += "Base = declarative_base()\n\n"
for table_name in inspector.get_table_names(schema=schema):
columns = inspector.get_columns(table_name, schema=schema)
pk = inspector.get_pk_constraint(table_name, schema=schema)
fks = inspector.get_foreign_keys(table_name, schema=schema)
# Class name: convert snake_case to PascalCase
class_name = ''.join(word.capitalize() for word in table_name.split('_'))
models_code += f"class {class_name}(Base):\n"
models_code += f" __tablename__ = '{table_name}'\n\n"
# Generate columns
for col in columns:
col_name = col['name']
col_type = str(col
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 Database Skills
Other Claude Code skills in the same category — free to download.
Migration Generator
Generate database migration files
Query Optimizer
Analyze and optimize slow database queries
Schema Designer
Design database schema from requirements
Seed Data Generator
Generate database seed/sample data
Index Advisor
Suggest database indexes based on query patterns
SQL to ORM
Convert raw SQL queries to ORM syntax
Database Backup Script
Create database backup and restore scripts
Connection Pool Setup
Configure database connection pooling
Want a Database 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.