anantbhandarkar/make-it-right/mir-backend-python-django
Claude Code and agent skill by anantbhandarkar/make-it-right
- community
- ext:[{"type":"hook","description":"Pre/post lifecycle hooks"}]
Checking that the SKILL.md file is still in the repository.
Make It Right (Django module). Django 6.1 / 5.2 LTS + Django REST Framework specific reliability augmentation. Use alongside the mir-backend skill when the target stack is Django — it carries the mechanical footguns that the framework-agnostic skill deliberately omits: ORM N+1 with select_related/prefetch_related and the new QuerySet.fetch_mode() (FETCH_PEERS / FETCH_RAISE), queryset laziness and result caching, migration safety on populated tables (lock_timeout, AddIndexConcurrently, db_default), transaction.atomic() and on_commit() boundaries, mass assignment through ModelForm and DRF serializers, async views and the async ORM (transactions do NOT work in async; CONN_MAX_AGE must be off), the built-in django.tasks background framework added in 6.0, signal side-effect traps, and Django's own 2026 security advisories. TRIGGER only when the Python backend stack is Django — building, reviewing, or debugging a Django view, model, serializer, migration, task, or admin. Always loads TOGETHER WITH mir-backend (the gates) and mir-backend-python (CPython runtime concerns: GIL, async/sync, fork-safety, cold start, packaging supply chain); this module only adds Django/DRF library mechanics. SKIP for FastAPI (mir-backend-python-fastapi), Flask (mir-backend-python-flask), any other non-Django stack, and non-Python runtimes.
Install
npx vskill@latest install anantbhandarkar/make-it-right/mir-backend-python-djangoSemi-extensibleMentions customization, but needs skill-specific knowledge. Read the extensible skills standard
SKILL.md
The same SKILL.md was published earlier as anantbhandarkar/make-it-right/mir-backend-python-django.
/mir-backend-python-django · Make It Right (Django)
Bottom tier of the chain: mir-backend (generic gates) → mir-backend-python (CPython runtime model) → this (Django/DRF library mechanics). Run the gates first; load the Python runtime tier for the concurrency/process model; reach for this at Gate 5 (design mechanics), Gate 6 (implementation), and Gate 7 review. Runtime-level concerns (GIL, async-vs-sync, blocking the event loop, fork-safe pools, cold start) live in `mir-backend-python` — not here.
Stack assumed, versions verified 13 Aug 2026:
| Version | Notes | ||
|---|---|---|---|
| Current release | Django 6.1, released 5 Aug 2026 | Mainstream support to Apr 2027, extended to Dec 2027. Requires Python 3.12–3.14. | |
| Current LTS | Django 5.2 LTS | Extended support to Apr 2028. Last line to support Python 3.10/3.11. | |
| Previous | Django 6.0 | Mainstream support ended 4 Aug 2026 — security-only now. | |
| Next LTS | Django 6.2 LTS, due Apr 2027 |
Django 6.1 also dropped PostgreSQL < 15, MySQL < 8.4, MariaDB < 10.11, and SQLite < 3.37. Rest of the stack: DRF · PostgreSQL (psycopg 3) · Celery, or the built-in django.tasks framework added in 6.0. Say which Django version the project is on before applying any of this — 5.2 and 6.1 differ materially in the ORM and in the background-task story.
The Django footguns AI walks into most
These are the stack-specific cousins of the failure-mode catalog. Each is something Django/DRF code gets wrong even when the logic is right.
1. ORM N+1 — the silent query multiplier
Accessing a related object inside a loop fires one query per iteration because the ORM resolves relations lazily by default. AI writes for order in orders: print(order.user.email) and ships an N+1 without noticing — the Django ORM makes it invisible until a profiler surfaces it.
select_related vs prefetch_related:
select_related(*fields)— for FK and one-to-one relations; performs a SQLJOIN, one query total. Use for "to-one" traversal depth you already know. In 6.1, calling `select_related()` with no arguments is deprecated — enumerate the fields.prefetch_related(*fields)— for many-to-many and reverse FK (one-to-many) relations; runs a separateINquery and stitches in Python. Use forManyToManyField,related_namereverse accessors, or deeply nested paths.- Combine both:
queryset.select_related("user").prefetch_related("tags").
Bound columns: only("id", "email") loads a sparse model (accessing an un-fetched field triggers a lazy query); defer("body") is the inverse. values("id", "email") returns dicts — no model overhead, no lazy traps, best for read-only serialization.
New in Django 6.1 — `QuerySet.fetch_mode()`. This changes what "forgot to eager-load" costs, and it is the first mechanical defence Django ships against this bug.
Mode (django.db.models) | Behaviour on accessing an unfetched FK or deferred field | |
|---|---|---|
FETCH_ONE | Default. One query for the current instance — the classic N+1. | |
FETCH_PEERS | Fetches the field for every instance that came from the same queryset, prefetch_related-style. Turns N+1 into 2 queries. | |
FETCH_RAISE | Raises django.core.exceptions.FieldFetchBlocked. |
Use FETCH_RAISE on hot read paths so the N+1 fails in CI rather than in production; use FETCH_PEERS (set on a custom Manager.get_queryset()) as the safety net elsewhere. FETCH_PEERS is not a substitute for select_related — it still costs an extra round trip and it only helps instances from one queryset.
Detection on 5.2 and earlier: django-debug-toolbar (dev), nplusone (test-time, raises on N+1 unless explicitly allowed), assertNumQueries in tests.
2. QuerySet laziness and caching — know what actually re-queries
A queryset is lazy: it hits the DB only on iteration, list(), len(), bool(), slicing an unevaluated queryset, or explicit evaluation. Once evaluated, the rows are cached on that queryset object in _result_cache.
What that means, precisely — this is where the common folklore is wrong:
if qs:followed byfor obj in qs:is one query, not two.__bool__evaluates and caches; the loop reuses the cache. The real cost is different:if qs:fetches every row and builds every model instance just to answer "any?". Use.exists()— a singleSELECT 1 … LIMIT 1.- The cache belongs to the object, not the query. Any method that returns a new queryset discards it —
.filter(),.exclude(),.order_by(),.all(). SoModel.objects.filter(x=1)written twice is two queries even though the SQL is identical. Assign it to a variable once. - Slicing an unevaluated queryset issues
LIMIT/OFFSETand returns a new queryset. Slicing an already evaluated one slices the cached list in Python. Same syntax, different cost. .count()on an unevaluated queryset issuesSELECT COUNT(*); on an evaluated one it useslen(_result_cache). So.count()when you don't need the rows,len(qs)when you already have them..iterator()bypasses the cache entirely and streams with a server-side cursor. Right for a million-row export; wrong if you iterate twice, because the second pass re-queries.
3. Migrations on populated tables — the big one
AI writes migrations as if the table is empty. On a table with millions of rows the danger is not usually the statement's own duration — it is that an `ACCESS EXCLUSIVE` lock request queues every other query behind it, including reads. One slow report holds the lock, your ALTER waits behind it, and everything else waits behind your ALTER.
Bound the wait first. In any migration touching an existing table:
If the lock can't be taken in 3 seconds the migration fails and you retry — instead of taking production down while it waits.
What is and is not expensive on a currently-supported Postgres:
| Operation | Cost | |
|---|---|---|
AddField with a constant default= | The ADD COLUMN itself is metadata-only on PG 11+. Brief lock. | |
AddField(..., db_default=...) (Django 5.0+) | Same, and the default lands in the schema, so old code inserting rows during a rolling deploy still gets a value. Prefer this over default= for rolling deploys. | |
AlterField making an existing nullable column NOT NULL | Full table scan under lock. The real hazard. | |
AddIndex (plain) | Blocks writes for the whole build. | |
AlterField changing the column type | Full table rewrite. | |
AddConstraint (unique / check / FK) | Validates every row under lock. |
Safe pattern for making a column NOT NULL — three separate migrations:
- Add the column nullable (
null=True), withdb_defaultif old code will insert rows before it deploys. - Backfill in a
RunPythonstep, in batches to bound transaction size:
``python def backfill(apps, schema_editor): Model = apps.get_model("myapp", "MyModel") batch = 1000 while True: ids = list(Model.objects.filter(new_field__isnull=True).values_list("id", flat=True)[:batch]) if not ids: break Model.objects.filter(id__in=ids).update(new_field="default_value") ` Always use the historical model from apps.get_model(...)`, never the imported one — the imported model is the current code's shape, which will not match when the migration replays on an old database.
AlterFieldto dropnull=True. To avoid the scan on PG 12+, first addCHECK (col IS NOT NULL) NOT VALIDandVALIDATE CONSTRAINTit viamigrations.RunSQLwrapped inmigrations.SeparateDatabaseAndState, so Django's state matches while the SQL does the cheap path.
Indexes on large tables: use AddIndexConcurrently (and RemoveIndexConcurrently) from django.contrib.postgres.operations in a migration with atomic = False:
An interrupted CONCURRENTLY build leaves an INVALID index that the planner ignores but writes still maintain, and re-running fails on the duplicate name. The retry is DROP INDEX CONCURRENTLY IF EXISTS … then rebuild — put it in the runbook.
Other rules:
- Keep schema and data migrations in separate files. A data migration holding a long transaction accumulates schema locks behind it.
- Always write
reverse_codeforRunPython, ormigrations.RunPython.noopwith a comment explaining why reversal is safe or impossible. DEFAULT_AUTO_FIELDdefaults toBigAutoFieldfrom Django 6.0 (it wasAutoField). New models get bigint PKs; existing projects that never set it explicitly will seemakemigrationspropose a change.- Run migrations as a single pre-deploy job, not from the app's entrypoint. N replicas booting at once means N concurrent
migrateruns racing.
4. Transactions — atomic blocks, on_commit, and side effects
Django wraps each request in a transaction only when ATOMIC_REQUESTS = True. Without it, you're in autocommit and every save() / update() commits immediately. AI often forgets to scope transactions explicitly.
`transaction.atomic()` — as a decorator or context manager, wraps a block in a SAVEPOINT (nested) or BEGIN (top-level). If an exception propagates, the whole block rolls back.
`transaction.on_commit()` — registers a callback that runs after the outermost transaction commits successfully. Use for any side effect that cannot be rolled back (send email, enqueue a task, push a webhook). Never enqueue tasks inside the atomic block — a rollback does not un-enqueue them.
This is the start of the file. Read the full SKILL.md on GitHub.
Security
- Security scanPassed, 95 of 100Pattern checks on the skill's files.
- Model reviewPassed
Quality evaluation
- Task evaluationNot runNo evaluation yet. Run one in Skill Studio.
Source
- SKILL.md in the repositoryCheckingskills/mir-backend-python-django/SKILL.md
Popularity
- Repository stars
- 15
- 7-day trend score
- 14
Stars and forks are for the whole GitHub repository, not this skill alone. Not refreshed yet.
Extension points
hookPre/post lifecycle hooks
Works with
Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.
- Claude Code
- Cursor
- GitHub Copilot
- Windsurf
- Codex
- Gemini CLI
- Cline
- Amp
- Roo Code
- Goose
- Continue
- Kilo Code
- Junie
- Trae
- OpenHands
- Qwen Code
- AI Agent
- Tabnine Chat
- Sourcegraph Cody
- Amazon Q
- Firebase Genkit
- Sweep
- Devin
- Phind
- Mentat
- Claude Desktop
- Aider
- GPT Pilot
- Plandex
- bolt.new
- v0
- Replit Agent
- Anse
- TypingMind
- BetterChatGPT
- LibreChat
- Warp AI
- Pieces
- Fig AI
Embed badge
[](https://verified-skill.com/skills/anantbhandarkar/make-it-right/mir-backend-python-django)