---
name: orm-model
description: Add or modify an ORM model and its relations, keeping schema and code in sync
category: database
---

# ORM Model

Use when adding a new model/entity or changing fields and relationships in an ORM (e.g. SQLAlchemy, Prisma, Django, ActiveRecord, TypeORM, Sequelize).

1. Read existing models to match the project's conventions: base class, naming, type mappings, and how relations are declared.
2. Define fields with explicit types, nullability, defaults, and constraints (unique, length, indexed) that mirror the intended schema.
3. Declare relations on both sides where the ORM supports it (e.g. `belongsTo`/`hasMany`), and set the cascade/`on_delete` behavior deliberately.
4. Generate or hand-write the migration that the model change implies, then review the generated DDL — don't trust autogen blindly.
5. Apply the migration to a dev database and confirm the model loads, relations traverse, and queries work.
6. Update serializers, validators, factories/seeds, and any type definitions that reference the changed fields.

## Rules
- Keep the model and the migration consistent; a model change without a matching migration is a silent drift bug.
- Set relation loading explicitly (eager vs lazy) and watch for N+1 queries on collections.
- Define cascade/`on_delete` intentionally rather than accepting the ORM default.
- Add DB-level constraints (unique, FK), not just app-level validation, for anything that must hold true.
- Review autogenerated migrations before applying — they can miss renames or produce destructive drops.
