anantbhandarkar/make-it-right/mir-backend-python-django

Claude Code and agent skill by anantbhandarkar/make-it-right

Trust tier 3
  • community
  • ext:[{"type":"hook","description":"Pre/post lifecycle hooks"}]
Source check pending

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-django

Semi-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:

VersionNotes
Current releaseDjango 6.1, released 5 Aug 2026Mainstream support to Apr 2027, extended to Dec 2027. Requires Python 3.12–3.14.
Current LTSDjango 5.2 LTSExtended support to Apr 2028. Last line to support Python 3.10/3.11.
PreviousDjango 6.0Mainstream support ended 4 Aug 2026 — security-only now.
Next LTSDjango 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 SQL JOIN, 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 separate IN query and stitches in Python. Use for ManyToManyField, related_name reverse 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.

python
# WRONG — N+1
orders = Order.objects.filter(status="pending")
for order in orders:
send_email(order.user.email) # query per iteration
# RIGHT
orders = Order.objects.filter(status="pending").select_related("user")
for order in orders:
send_email(order.user.email) # no extra queries

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_ONEDefault. One query for the current instance — the classic N+1.
FETCH_PEERSFetches the field for every instance that came from the same queryset, prefetch_related-style. Turns N+1 into 2 queries.
FETCH_RAISERaises django.core.exceptions.FieldFetchBlocked.
python
from django.db import models
# Turn accidental lazy loads into a hard failure on a performance-critical path
for book in Book.objects.fetch_mode(models.FETCH_RAISE):
print(book.author.name) # 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 by for 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 single SELECT 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(). So Model.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/OFFSET and returns a new queryset. Slicing an already evaluated one slices the cached list in Python. Same syntax, different cost.
  • .count() on an unevaluated queryset issues SELECT COUNT(*); on an evaluated one it uses len(_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.
python
# WRONG — two queries, because .filter() builds a new queryset each time
if MyModel.objects.filter(active=True).exists():
for obj in MyModel.objects.filter(active=True):
...
# RIGHT — one queryset object, one query, cached
qs = MyModel.objects.filter(active=True)
for obj in qs:
...
# RIGHT — existence only, no rows built
if MyModel.objects.filter(active=True).exists(): # SELECT 1 … LIMIT 1
...
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:

python
operations = [migrations.RunSQL("SET lock_timeout = '3s'", reverse_sql=migrations.RunSQL.noop), ...]

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:

OperationCost
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 NULLFull table scan under lock. The real hazard.
AddIndex (plain)Blocks writes for the whole build.
AlterField changing the column typeFull table rewrite.
AddConstraint (unique / check / FK)Validates every row under lock.

Safe pattern for making a column NOT NULL — three separate migrations:

  1. Add the column nullable (null=True), with db_default if old code will insert rows before it deploys.
  2. Backfill in a RunPython step, 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.

  1. AlterField to drop null=True. To avoid the scan on PG 12+, first add CHECK (col IS NOT NULL) NOT VALID and VALIDATE CONSTRAINT it via migrations.RunSQL wrapped in migrations.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:

python
from django.contrib.postgres.operations import AddIndexConcurrently
class Migration(migrations.Migration):
atomic = False # required for CONCURRENTLY
operations = [
AddIndexConcurrently(
model_name="order",
index=models.Index(fields=["status"], name="order_status_idx"),
),
]

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_code for RunPython, or migrations.RunPython.noop with a comment explaining why reversal is safe or impossible.
  • DEFAULT_AUTO_FIELD defaults to BigAutoField from Django 6.0 (it was AutoField). New models get bigint PKs; existing projects that never set it explicitly will see makemigrations propose a change.
  • Run migrations as a single pre-deploy job, not from the app's entrypoint. N replicas booting at once means N concurrent migrate runs 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.

python
from django.db import transaction
@transaction.atomic
def transfer(from_account, to_account, amount):
from_account.balance -= amount
from_account.save()
to_account.balance += amount
to_account.save() # if this raises, both saves roll 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.

python
# WRONG — task fires even on rollback
with transaction.atomic():
order.save()
send_receipt_task.delay(order.id) # may run even if save rolls back
# RIGHT
with transaction.atomic():
order.save()
transaction.on_commit(lambda: send_receipt_task.delay(order.id))

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

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
vskill VERIFIED badge
[![vskill VERIFIED](https://verified-skill.com/api/v1/skills/anantbhandarkar/make-it-right/mir-backend-python-django/badge)](https://verified-skill.com/skills/anantbhandarkar/make-it-right/mir-backend-python-django)

Something wrong with this skill or its page? Tell us.