Backend Models Standards

Define database models with clear naming, appropriate data types, constraints, relationships, and validation at multiple layers. Use this skill when creating or modifying database model files, ORM classes, schema definitions, or data model relationships. Apply when working with model files (e.g., models.py, models/, ActiveRecord classes, Prisma schema, Sequelize models), defining table structures, setting up foreign keys and relationships, configuring cascade behaviors, implementing model validations, adding timestamps, or working with database constraints (NOT NULL, UNIQUE, foreign keys). Use for any task involving data integrity enforcement, relationship definitions, or model-level data validation.

153 stars

Best use case

Backend Models Standards is best used when you need a repeatable AI agent workflow instead of a one-off prompt.

Define database models with clear naming, appropriate data types, constraints, relationships, and validation at multiple layers. Use this skill when creating or modifying database model files, ORM classes, schema definitions, or data model relationships. Apply when working with model files (e.g., models.py, models/, ActiveRecord classes, Prisma schema, Sequelize models), defining table structures, setting up foreign keys and relationships, configuring cascade behaviors, implementing model validations, adding timestamps, or working with database constraints (NOT NULL, UNIQUE, foreign keys). Use for any task involving data integrity enforcement, relationship definitions, or model-level data validation.

Teams using Backend Models Standards should expect a more consistent output, faster repeated execution, less prompt rewriting.

When to use this skill

  • You want a reusable workflow that can be run more than once with consistent structure.

When not to use this skill

  • You only need a quick one-off answer and do not need a reusable workflow.
  • You cannot install or maintain the underlying files, dependencies, or repository context.

Installation

Claude Code / Cursor / Codex

$curl -o ~/.claude/skills/backend-models-standards/SKILL.md --create-dirs "https://raw.githubusercontent.com/Microck/ordinary-claude-skills/main/skills_all/backend-models-standards/SKILL.md"

Manual Installation

  1. Download SKILL.md from GitHub
  2. Place it in .claude/skills/backend-models-standards/SKILL.md inside your project
  3. Restart your AI agent — it will auto-discover the skill

How Backend Models Standards Compares

Feature / AgentBackend Models StandardsStandard Approach
Platform SupportNot specifiedLimited / Varies
Context Awareness High Baseline
Installation ComplexityUnknownN/A

Frequently Asked Questions

What does this skill do?

Define database models with clear naming, appropriate data types, constraints, relationships, and validation at multiple layers. Use this skill when creating or modifying database model files, ORM classes, schema definitions, or data model relationships. Apply when working with model files (e.g., models.py, models/, ActiveRecord classes, Prisma schema, Sequelize models), defining table structures, setting up foreign keys and relationships, configuring cascade behaviors, implementing model validations, adding timestamps, or working with database constraints (NOT NULL, UNIQUE, foreign keys). Use for any task involving data integrity enforcement, relationship definitions, or model-level data validation.

Where can I find the source code?

You can find the source code on GitHub using the link provided at the top of the page.

SKILL.md Source

# Backend Models Standards

**Core Rule:** Models define data structure and integrity. Keep them focused on data representation, not business logic.

## When to use this skill

- When creating or modifying database model files (models.py, models/, schema.prisma, etc.)
- When defining ORM classes or ActiveRecord models for database tables
- When establishing table relationships (one-to-many, many-to-many, has-many, belongs-to)
- When configuring foreign keys, indexes, and cascade behaviors
- When implementing model-level validation rules
- When adding timestamp fields (created_at, updated_at) for auditing
- When setting database constraints (NOT NULL, UNIQUE, CHECK constraints)
- When choosing appropriate data types for model fields
- When balancing normalization with query performance needs
- When defining model methods or scopes for common queries

This Skill provides Claude Code with specific guidance on how to adhere to coding standards as they relate to how it should handle backend models.

## Naming Conventions

**Models:** Singular, PascalCase (`User`, `OrderItem`, `PaymentMethod`)

**Tables:** Plural, snake_case (`users`, `order_items`, `payment_methods`)

**Relationships:** Descriptive and clear
- `user.orders` (one-to-many)
- `order.items` (one-to-many)
- `product.categories` (many-to-many)

**Avoid generic names:** `data`, `info`, `record`, `entity`

## Required Fields

**Timestamps on every model:**
```python
created_at = Column(DateTime, nullable=False, default=datetime.utcnow)
updated_at = Column(DateTime, nullable=False, default=datetime.utcnow, onupdate=datetime.utcnow)
```

**Primary keys:** Always explicit, prefer UUIDs for distributed systems or auto-incrementing integers for simplicity

**Why:** Auditing, debugging, data lineage tracking, soft deletes

## Data Integrity - Database Level

**Use constraints, not just application validation:**

```python
# NOT NULL for required fields
email = Column(String(255), nullable=False)

# UNIQUE constraints
email = Column(String(255), unique=True, nullable=False)

# CHECK constraints for business rules
age = Column(Integer, CheckConstraint('age >= 18'))

# Foreign keys with explicit cascade behavior
user_id = Column(Integer, ForeignKey('users.id', ondelete='CASCADE'))
```

**Why:** Database enforces rules even if application code bypassed. Defense in depth.

## Data Types - Choose Appropriately

| Data       | Type               | Avoid       |
| ---------- | ------------------ | ----------- |
| Email, URL | VARCHAR(255)       | TEXT        |
| Short text | VARCHAR(n)         | TEXT        |
| Long text  | TEXT               | VARCHAR     |
| Money      | DECIMAL(10,2)      | FLOAT       |
| Boolean    | BOOLEAN            | TINYINT     |
| Timestamps | TIMESTAMP/DATETIME | VARCHAR     |
| JSON data  | JSON/JSONB         | TEXT        |
| UUIDs      | UUID               | VARCHAR(36) |

**Why:** Correct types enable database optimizations, constraints, and prevent data corruption.

## Indexes - Performance Critical

**Always index:**
- Primary keys (automatic)
- Foreign keys (manual in most ORMs)
- Columns in WHERE clauses
- Columns in JOIN conditions
- Columns in ORDER BY clauses

**Example:**
```python
class Order(Base):
    __tablename__ = 'orders'
    
    id = Column(Integer, primary_key=True)
    user_id = Column(Integer, ForeignKey('users.id'), index=True)
    status = Column(String(50), index=True)  # Frequently filtered
    created_at = Column(DateTime, index=True)  # Frequently sorted
```

**Don't over-index:** Each index slows writes. Index only queried columns.

## Relationships - Explicit Configuration

**Define both sides of relationships:**

```python
# One-to-many
class User(Base):
    orders = relationship('Order', back_populates='user', cascade='all, delete-orphan')

class Order(Base):
    user_id = Column(Integer, ForeignKey('users.id'))
    user = relationship('User', back_populates='orders')
```

**Cascade behaviors:**
- `CASCADE`: Delete related records (user deleted → orders deleted)
- `SET NULL`: Nullify foreign key (category deleted → product.category_id = NULL)
- `RESTRICT`: Prevent deletion if related records exist
- `NO ACTION`: Database default, usually same as RESTRICT

**Choose based on business logic, not convenience.**

## Validation - Two Layers

**Model-level validation (application):**
```python
@validates('email')
def validate_email(self, key, email):
    if not re.match(r'^[^@]+@[^@]+\.[^@]+$', email):
        raise ValueError('Invalid email format')
    return email
```

**Database-level constraints (see Data Integrity section)**

**Why both:** Model validation provides clear error messages. Database constraints prevent data corruption if application bypassed.

## What Belongs in Models

**YES:**
- Field definitions and types
- Relationships to other models
- Simple property methods (`@property def full_name`)
- Data validation rules
- Database constraints

**NO:**
- Business logic (move to service layer)
- External API calls
- Complex calculations (move to service methods)
- Email sending, file uploads, etc.

**Models represent data structure, not behavior.**

## Normalization vs Performance

**Normalize when:**
- Data has clear entity boundaries
- Updates need to propagate (user email changes once)
- Avoiding data duplication is critical

**Denormalize when:**
- Read performance critical (analytics, reporting)
- Data rarely changes (historical snapshots)
- Joins become too expensive

**Default to normalized. Denormalize only with evidence of performance issues.**

## Common Patterns

**Soft deletes:**
```python
deleted_at = Column(DateTime, nullable=True, index=True)

# Query only active records
query = session.query(User).filter(User.deleted_at.is_(None))
```

**Polymorphic associations:**
```python
# Avoid if possible - complex and hard to maintain
# Prefer separate relationship fields or inheritance
```

**Enums for fixed values:**
```python
from enum import Enum

class OrderStatus(str, Enum):
    PENDING = 'pending'
    PAID = 'paid'
    SHIPPED = 'shipped'
    DELIVERED = 'delivered'

status = Column(Enum(OrderStatus), nullable=False, default=OrderStatus.PENDING)
```

## Testing Models

**Test constraints and validation:**
```python
def test_user_email_required():
    with pytest.raises(IntegrityError):
        user = User(name='Test')
        session.add(user)
        session.commit()

def test_user_email_unique():
    user1 = User(email='test@example.com')
    user2 = User(email='test@example.com')
    session.add(user1)
    session.commit()
    
    with pytest.raises(IntegrityError):
        session.add(user2)
        session.commit()
```

**Test relationships:**
```python
def test_user_orders_cascade_delete():
    user = User(email='test@example.com')
    order = Order(user=user)
    session.add(user)
    session.commit()
    
    session.delete(user)
    session.commit()
    
    assert session.query(Order).count() == 0
```

## Checklist for New Models

- [ ] Singular model name, plural table name
- [ ] Primary key defined
- [ ] `created_at` and `updated_at` timestamps
- [ ] NOT NULL on required fields
- [ ] UNIQUE constraints where appropriate
- [ ] Foreign keys with explicit cascade behavior
- [ ] Indexes on foreign keys and queried columns
- [ ] Appropriate data types (not all VARCHAR)
- [ ] Validation at model and database levels
- [ ] Relationships defined on both sides
- [ ] Tests for constraints and validation

Related Skills

nodejs-backend-patterns

153
from Microck/ordinary-claude-skills

Build production-ready Node.js backend services with Express/Fastify, implementing middleware patterns, error handling, authentication, database integration, and API design best practices. Use when creating Node.js servers, REST APIs, GraphQL backends, or microservices architectures.

nft-standards

153
from Microck/ordinary-claude-skills

Implement NFT standards (ERC-721, ERC-1155) with proper metadata handling, minting strategies, and marketplace integration. Use when creating NFT contracts, building NFT marketplaces, or implementing digital asset systems.

creating-financial-models

153
from Microck/ordinary-claude-skills

This skill provides an advanced financial modeling suite with DCF analysis, sensitivity testing, Monte Carlo simulations, and scenario planning for investment decisions

statsmodels

153
from Microck/ordinary-claude-skills

Statistical modeling toolkit. OLS, GLM, logistic, ARIMA, time series, hypothesis tests, diagnostics, AIC/BIC, for rigorous statistical inference and econometric analysis.

Backend Migration Standards

153
from Microck/ordinary-claude-skills

Create and manage database migrations with reversible changes, proper naming conventions, and zero-downtime deployment strategies. Use this skill when creating database migration files, modifying schema, adding or removing tables/columns, managing indexes, or handling data migrations. Apply when working with migration files (e.g., db/migrate/, migrations/, alembic/, sequelize migrations), schema changes, database versioning, rollback implementations, or when you need to ensure backwards compatibility during deployments. Use for any task involving database structure changes, index creation, constraint modifications, or data transformation scripts.

backend-dev-guidelines

153
from Microck/ordinary-claude-skills

Comprehensive backend development guide for Langfuse's Next.js 14/tRPC/Express/TypeScript monorepo. Use when creating tRPC routers, public API endpoints, BullMQ queue processors, services, or working with tRPC procedures, Next.js API routes, Prisma database access, ClickHouse analytics queries, Redis queues, OpenTelemetry instrumentation, Zod v4 validation, env.mjs configuration, tenant isolation patterns, or async patterns. Covers layered architecture (tRPC procedures → services, queue processors → services), dual database system (PostgreSQL + ClickHouse), projectId filtering for multi-tenant isolation, traceException error handling, observability patterns, and testing strategies (Jest for web, vitest for worker).

backend-ai-guide

153
from Microck/ordinary-claude-skills

|

zapier-workflows

153
from Microck/ordinary-claude-skills

Manage and trigger pre-built Zapier workflows and MCP tool orchestration. Use when user mentions workflows, Zaps, automations, daily digest, research, search, lead tracking, expenses, or asks to "run" any process. Also handles Perplexity-based research and Google Sheets data tracking.

writing-skills

153
from Microck/ordinary-claude-skills

Create and manage Claude Code skills in HASH repository following Anthropic best practices. Use when creating new skills, modifying skill-rules.json, understanding trigger patterns, working with hooks, debugging skill activation, or implementing progressive disclosure. Covers skill structure, YAML frontmatter, trigger types (keywords, intent patterns), UserPromptSubmit hook, and the 500-line rule. Includes validation and debugging with SKILL_DEBUG. Examples include rust-error-stack, cargo-dependencies, and rust-documentation skills.

writing-plans

153
from Microck/ordinary-claude-skills

Use when design is complete and you need detailed implementation tasks for engineers with zero codebase context - creates comprehensive implementation plans with exact file paths, complete code examples, and verification steps assuming engineer has minimal domain knowledge

workflow-orchestration-patterns

153
from Microck/ordinary-claude-skills

Design durable workflows with Temporal for distributed systems. Covers workflow vs activity separation, saga patterns, state management, and determinism constraints. Use when building long-running processes, distributed transactions, or microservice orchestration.

workflow-management

153
from Microck/ordinary-claude-skills

Create, debug, or modify QStash workflows for data updates and social media posting in the API service. Use when adding new automated jobs, fixing workflow errors, or updating scheduling logic.