Django Best Practices Guide

VerifiedSafe

A strict guide to writing correct and performant Django and DRF code, covering models, ORM, DRF, Celery, Channels, caching, and tests.

Sby Skills Guide Bot
DevelopmentAdvanced
7/22/2026
Claude Code
#django#django-rest-framework#orm#performance#backend

Recommended for

Automated summary

Provides a strict checklist and rewrite guidance for Django and DRF code, covering ORM queries, architecture, APIs, async, security, caching, migrations, and tests.

Strengths

  • Covers 15 rule domains with specific citable rule IDs during review
  • Flags common anti-patterns such as N+1 loops, fat views, and synchronous ORM calls inside async code
  • Generates production-ready fixes with inline reasoning comments
  • Groups review findings by severity (CRITICAL, HIGH, MEDIUM) while citing the violated rule

Limitations

  • Relies on AGENTS.md or the rules/ directory being available to apply detailed rules
  • Enforces deliberately strict conventions that may conflict with an existing team style
  • Focuses on Django/DRF and does not cover general Python best practices outside that scope
When to use it

Use it to review, refactor, or generate Django/DRF code with performance, concurrency, and architecture constraints.

When not to use it

Avoid it on Django projects with very different conventions or for general Python questions unrelated to Django.

Security analysis

Safe
Quality score86/100

Contains only Django/DRF best-practice guidance and code review instructions; no commands, network calls, secret handling, or destructive actions.

No concerns found

How this analysis is made

Examples

Review Django view for N+1 queries
Review this Django view and serializer for N+1 queries and missing select_related/prefetch_related. Group findings by severity and cite the rule IDs.
Refactor DRF API
Refactor this DRF viewset and serializer to follow Django best practices, including pagination, query optimization, and service-layer separation.
Write idempotent Celery task
Write an idempotent Celery task for marking an order as paid, with select_for_update and safe retry behavior explained in comments.

name: django-best-practices description: > Django and Django REST Framework best practices guide. Use this skill to review, optimize, architect, and write performant Django applications. Triggers when the user asks to implement or review Django models, ORM queries, DRF APIs, Celery tasks, background workers, WebSockets (Channels), caching logic, or tests. globs:

  • "**/*.py"
  • "**/models.py"
  • "**/views.py"
  • "**/serializers.py"
  • "**/tasks.py"
  • "**/consumers.py"
  • "**/tests/*.py"

Django Best Practices Tool Wrapper & Reviewer

A strict guide to writing correct and performant Django and DRF code. Based on real-world patterns, the HackSoftware Styleguide, and common architectural pitfalls.

Context

This skill is the final word on Django design constraints. It covers 15 core categories of real-world expertise (like zero-downtime migrations, avoiding ORM locks, and decoupling business logic). Treat these patterns as strict rules rather than suggestions.

Instructions

Whenever you write new Django code, modify existing architecture, or refactor for performance:

  1. Identify the Domain: Determine which components you are touching (e.g., DB schema, REST API, Celery, Channels, caching, security).
  2. Source the Expertise:
    • Read AGENTS.md (the compiled reference containing all 15 rule domains).
    • Or read the specific markdown rules in the rules/ directory (e.g., rules/orm-queries.md, rules/architecture.md).
  3. Audit against Anti-Patterns: Check the codebase against the ❌ Wrong blocks documented in the guidelines. Look out for:
    • Implicit N+1 loops (missing select_related/prefetch_related).
    • Fat views instead of fat models or services.
    • Synchronous ORM calls inside async def views or Channels without sync_to_async.
    • Business logic hidden inside post_save signals.
  4. Implement the Correct Pattern: Rewrite or generate code that follows the ✅ Right patterns. Follow all architectural notes and constraints.
  5. Handle Edge Cases & Failure Modes:
    • When writing queue workers, use select_for_update(skip_locked=True) to prevent deadlocks.
    • When writing Celery tasks, enforce explicit idempotency (order.paid = True).
    • When creating migrations for large tables, separate schema additions from data backfills to handle downtime risks.
  6. Format Your Output:
    • For Code Generation: Write explicit, production-ready code with short inline comments explaining your reasoning (e.g., "# Atomically lock the row to avoid lost update race conditions").
    • For Code Review: Output your findings as a checklist grouped by severity (e.g., CRITICAL, HIGH, MEDIUM). For every violation, cite the exact rule prefix (e.g., orm-nplusone) and print the recommended fix.

Quick Reference / Known Rules

  • Category 1 (Database & Queries): orm-nplusone, orm-only-defer, orm-laziness, orm-explain
  • Category 2 (Database Locks): orm-select-for-update, orm-select-for-update-nowait, orm-f-expressions, orm-bulk-inserts
  • Category 3 (Architecture): arch-services-layer, model-fat-models, arch-selectors
  • Category 4 (APIs): views-fbv-vs-cbv, api-drf-serializers, api-viewset-optimization, api-pagination
  • Category 5 (Async & Channels): async-celery-idempotency, async-django-views, channels-sync-to-async, channels-security-auth
  • Category 6 (Security & Caching): security-uuids-in-urls, security-env-secrets, security-csrf, caching-layer
  • Category 7 (Migrations & Test): migrations-runpython, test-pytest-fixtures, test-query-counts

Examples

Example Review Output:

### ❌ CRITICAL: N+1 Query Detected (`orm-nplusone`)
The current mapping loops over `Author.objects.all()` and accesses `author.books.count()`. This triggers 101 queries for 100 authors.
**Recommendation:** Use the database to aggregate this mathematically:
`Author.objects.annotate(book_count=Count('books'))`

Example Code Generation (Celery Idempotency):

@shared_task
def process_payment(order_id, amount):
    # Rule applied: async-celery-idempotency - Protect against multiple concurrent executions
    order = Order.objects.get(id=order_id)
    if order.paid:
        return

From the file to a first result

The download contains exactly the content displayed on this page. This copy may differ from the latest version in the source repository.

View the source and supporting files

This download contains SKILL.md only. Any scripts, references, templates and dependencies are not included. Get the required files from the source, preserving their directory structure, before continuing.

1. Download the file

Download SKILL.md

From the root of a test project, save the file as .skill-downloads/django-best-practices-guide-mrwakbvk/SKILL.md, or use the command below. This folder is for inspecting the skill before installation.

Command for macOS/Linux or WSL: requires a POSIX shell and curl. On Windows without WSL, use the download button and create the folder manually.

mkdir -p '.skill-downloads/django-best-practices-guide-mrwakbvk' && curl --fail --show-error --location 'https://skills-guides.com/api/skills/django-best-practices-guide-mrwakbvk/download' --output '.skill-downloads/django-best-practices-guide-mrwakbvk/SKILL.md.part' && mv '.skill-downloads/django-best-practices-guide-mrwakbvk/SKILL.md.part' '.skill-downloads/django-best-practices-guide-mrwakbvk/SKILL.md'

2. Check prerequisites

Read SKILL.md before using it. If it references scripts or external services, inspect them and prepare the required access in your test environment.

No recognized prerequisites section in this file. This does not mean it is self-contained: libraries, tools and access requirements may be mentioned elsewhere in the content or source repository.

The platforms on this page are catalog indications. The paths below follow tool documentation; they do not prove this skill has been run in those tools. No minimum tool version is confirmed for this listing.

3. Load the skill

After inspection, copy the complete folder into your project using one of the commands below, then open a new tool session. The command stops if a folder with the same name already exists: compare the files before replacing it.

Claude Code
test -f '.skill-downloads/django-best-practices-guide-mrwakbvk/SKILL.md' && test -s '.skill-downloads/django-best-practices-guide-mrwakbvk/SKILL.md' && mkdir -p '.claude/skills' && test ! -e '.claude/skills/django-best-practices' && cp -R '.skill-downloads/django-best-practices-guide-mrwakbvk' '.claude/skills/django-best-practices'

OpenSkills

OpenSkills must already be installed. The local install/read procedure is checked with OpenSkills 1.5.0, which requires Node.js ≥ 20.6.0. Catalog slugs are not resolved automatically.

Official OpenSkills installation
openskills install './.skill-downloads/django-best-practices-guide-mrwakbvk'

openskills read 'django-best-practices-guide-mrwakbvk'

Reading should display the installed file content and its base directory. It does not run the skill or install its dependencies.

For an agent that reads AGENTS.md, then sync the index. This command changes AGENTS.md: review the diff before using it.

openskills sync

Manual method or another tool: attach SKILL.md to a conversation, or open it in an agent that can read files. Include any required supporting resources. No universal folder is recognized by every tool.

4. Try a first task

Use a short, synthetic input: an API endpoint, a small document or an interface brief. In a new conversation, attach the file or give the agent its path, then adapt this request:

Read .skill-downloads/django-best-practices-guide-mrwakbvk/SKILL.md and apply its instructions to this example: [describe a test input]. Identify any missing files, dependencies or access. Produce the result requested by the skill without inventing data or running unreviewed scripts.

Expected result: output matching the skill instructions, or a precise list of missing prerequisites. A read confirmation alone does not validate a first use. If an external resource is unavailable, that path remains untested.

Related skills