migrations
Skill1 starsChanged 5 months agoMITView on GitHub
Writes safe schema and data migrations for Django 5.2 on PostgreSQL — data backfills via RunPython with apps.get_model, reversible operations, tenant-aware per-entreprise batching, expand-contract column renames, and concurrent index creation. Use when adding or reviewing a migration, backfilling a column, renaming or dropping a field without downtime, wiring makemigrations --check into CI, or asking how to migrate safely here. Not for the model/ViewSet change that triggers the migration (see multi-tenancy) or lock/transaction concurrency at request time (see db-concurrency).
3 other projects use a version of this.
Adopted by
Most recently taken up by
- theopenco/llmgatewaytheir own version, first seen Oct 1, 2026
- nahid-sparktales/agent-dispatchertheir own version, first seen Sep 21, 2026
- butterbase-ai/butterbase-skillstheir own version, first seen Jun 10, 2026
Other versions3 projects use a version of this.
Word for word · 0
None found.
Edited · 0
None found.
Wrote their own version · 3
- theopenco/llmgateway★ 1.7ksame name
- butterbase-ai/butterbase-skills★ 533same name
- nahid-sparktales/agent-dispatcher★ 59same name
How matches are found. Word for word: the exact same text. Edited: shares passages with this file (“99% same” means 99% of its five-word phrases also appear here; 10% or more counts). Their own version: similar meaning, or, weakest, the same name. We can’t tell which project had it first. Projects are counted among the 200 most-starred candidates, and mentions are links to the repository we found, up to 50 per site, so both counts are a floor.
In this repository49 other files it gives its agents.
- accessibilitySkill
- ai-evalsSkill
- ai-integrationSkill
- architecture-decisionsSkill
- audit-loggingSkill
- aws-servicesSkill
- browser-e2e-testingSkill
- celery-tasksSkill
- changelogSkill
- ci-cdSkill
- codebase-guideSkill
- code-reviewSkill
- commit-messageSkill
- cookie-auth-csrfSkill
- dashboard-data-designSkill
- db-concurrencySkill
- debugSkill
- dependency-auditSkill
- deploy-awsSkill
- design-systemSkill
- drf-apiSkill
- drf-zod-contractSkill
- frontend-perfSkill
- git-workflowSkill
- i18n-rtlSkill
- incident-responseSkill
- money-decimalSkill
- multi-tenancySkill
- nextjs-moduleSkill
- observabilitySkill
- perf-reviewSkill
- production-readinessSkill
- product-ux-designSkill
- rbac-permissionsSkill
- react-querySkill
- security-reviewSkill
- skill-authoringSkill
- tailwind-shadcnSkill
- tenant-session-switchSkill
- threat-modelingSkill
- verifySkill
- version-checkSkill
- visual-ui-designSkill
- webhook-handlerSkill
- websockets-channelsSkill
- write-testsSkill
- zod-formsSkill
- zustand-stateSkill
- example-skillSkill
The file
We split this skill into the rules it gives an agent
4 rules. About 0 are common, 0 are distinctive, and 4 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈0
Distinctive · estimate
This author's own choices. Worth a look.
4
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Very specific: line 17
Data migrations are reversible and idempotent: Every RunPython gets a real reverse callable (or RunPython.noop), and re-running it is a …
- Very specific: line 29
Never import models at module top level in a data migration: Use the historical model via apps.get_model, give a reverse, and make it …
- Very specific: line 107
Run python manage.py makemigrations --check --dry-run in CI so a model change that forgot its migration fails the build (see ci-cd).
- Very specific: line 112
Never edit a migration that is already applied or committed — add a new forward migration.
≈ “Common” is an estimate: at least 1 in 5 of the 213,897 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
Migrations (safe schema and data change on PostgreSQL)
When to use
Any time a change produces a new migration — a new column, a data backfill, a
rename, a drop, or an index. On PostgreSQL a careless migration takes an
ACCESS EXCLUSIVE lock or rewrites a large table, so treat "does this block
writes in prod?" as a review question, not an afterthought.
Pattern
Two invariants hold everywhere:
- Data migrations are reversible and idempotent. Every
RunPythongets a real reverse callable (orRunPython.noop), and re-running it is a no-op — never assume it runs exactly once on clean state. - Schema changes that lock or rewrite are split (expand-contract). Add the new shape, backfill, switch reads/writes, then drop the old shape in a later deploy — so no single migration takes a long exclusive lock.
Tenant data lives under entreprise, so backfills iterate per tenant in batches
rather than loading one giant queryset.
Steps / idioms
Never import models at module top level in a data migration. Use the historical model via
apps.get_model, give a reverse, and make it idempotent:from django.db import migrations def backfill_slug(apps, schema_editor): Invoice = apps.get_model("billing", "Invoice") # historical model, not the import # tenant-aware: iterate per entreprise, batch to bound memory + lock time for ent_id in Invoice.objects.values_list("entreprise_id", flat=True).distinct(): qs = Invoice.objects.filter(entreprise_id=ent_id, slug="") # idempotent: only unset rows for inv in qs.iterator(chunk_size=500): inv.slug = f"inv-{inv.pk}" inv.save(update_fields=["slug"]) def unset_slug(apps, schema_editor): Invoice = apps.get_model("billing", "Invoice") # reverse ONLY the rows this migration generated; leave pre-existing slugs alone. # An unconditional .update(slug="") would destroy slugs the forward step never wrote. for ent_id in Invoice.objects.values_list("entreprise_id", flat=True).distinct(): qs = Invoice.objects.filter(entreprise_id=ent_id).exclude(slug="") for inv in qs.iterator(chunk_size=500): if inv.slug == f"inv-{inv.pk}": # our value, not the user's inv.slug = "" inv.save(update_fields=["slug"]) class Migration(migrations.Migration): dependencies = [("billing", "0007_invoice_slug")] operations = [migrations.RunPython(backfill_slug, unset_slug)]A reverse must undo only what the forward step did. If the generated value is not recognisable, do not guess — declare it:
migrations.RunPython(backfill_slug, migrations.RunPython.noop) # intentionally irreversible: cannot distinguish generated slugs from pre-existing ones.- Split schema from data. One migration adds the nullable/blank column; a
separate
RunPythonbackfills; a later migration addsNOT NULL/constraints. Mixing DDL and a long data loop in one migration holds the lock the whole time. - Add indexes concurrently on hot tables so writes are not blocked. Use
AddIndexConcurrently(fromdjango.contrib.postgres.operations) and setatomic = Falseon theMigration—CREATE INDEX CONCURRENTLYcannot run inside a transaction. Pass the model name, not the app label.
Expand-contract (zero-downtime rename)
A single RenameField rewrites nothing but breaks any running old code mid-deploy.
Split across releases instead:
- Expand — add the new column; dual-write to both old and new in app code.
- Backfill —
RunPythoncopies old to new per entreprise, in batches. - Switch — ship code that reads/writes only the new column.
- Contract — a later migration drops the old column, once no code references it.
Each step is independently deployable and reversible. Never collapse them.
Adapt to your repo
Rename entreprise/Invoice/billing and the app label to match your project.
Confirm whether your table is large enough to need atomic = False + concurrent
indexes (small tables are fine with a plain AddIndex). Pick chunk_size to fit
your row width. If a backfill is huge, run it as an idempotent management command
or celery-task and keep the migration to schema only.
Gotchas
- Importing the app model directly (
from billing.models import Invoice) breaks when the migration replays against old state — alwaysapps.get_model. - A
RunPythonwith no reverse blocksmigratefrom rolling back; passRunPython.noopwhen the change genuinely cannot be undone. - A reverse that is broader than its forward is data loss, not a rollback. If the
forward only touched unset rows, the reverse must only reset rows it generated —
an unconditional
Model.objects.update(field="")wipes values that predate the migration, across every tenant, and no error is raised. When you cannot tell your value from the user's,RunPython.noopplus an explicit "intentionally irreversible" comment is the honest reverse. CREATE INDEX CONCURRENTLYfails inside a transaction — it needsatomic = False, and a failed concurrent index leaves anINVALIDindex you must drop by hand.- Adding a
NOT NULLcolumn with a default on a big table rewrites it under a lock; add nullable, backfill, then setNOT NULLin a follow-up. - Run
python manage.py makemigrations --check --dry-runin CI so a model change that forgot its migration fails the build (seeci-cd). - On a multi-instance or rolling deploy, run
migrateas a single leader-only step (one instance), never on every instance's startup — concurrentmigrateruns race the migration ledger and can deadlock or double-apply. - Never edit a migration that is already applied or committed — add a new forward
migration. Two branches that each add a migration to one app clash; resolve with
makemigrations --mergeand rebase.--fakemarks a migration applied without running it — safe only when the DB already matches that state, otherwise it silently skips the real schema change. - Decide where a data change lives. A one-time backfill tied to this schema
change belongs in
RunPythonin the migration; evolving reference/config data belongs in an idempotent, re-runnable seed management command (not a migration — migrations are frozen and replay everywhere forever); a one-off repair of bad data belongs in a run-once fix command.
See also
multi-tenancydb-concurrencyci-cd
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

