| name | django-patterns |
| type | reference |
| description | Provides expert-level Django development patterns covering App Router (indirectly via REST/GraphQL), async views, DRF, Celery, signals, middleware, and performance optimization. Use when building complex Django 5.x applications or identifying N+1 query issues. |
| paths | ["**/*.py","**/manage.py","**/settings.py","**/urls.py","**/serializers.py"] |
| effort | 3 |
| allowed-tools | Read, Glob, Grep, Write, Edit, Bash |
| user-invocable | true |
| when_to_use | When building Django 5.x applications requiring async support, background tasks (Celery), real-time features (Channels), or advanced ORM optimization. |
Django & DRF Professional Patterns
Core Expertise
- Modern Django: 5.x features, async views/middleware, ASGI deployment.
- Background & Real-time: Celery integration, Django Channels.
- ORM Optimization: select_related, prefetch_related, custom managers.
- Security: JWT auth, OAuth2, RBAC, protection against SQLi/XSS/CSRF.
Critical rules (non-obvious)
- N+1 queries: always use
select_related (FK) / prefetch_related (M2M) — never iterate and query inside loops
get_or_create race condition: wrap in transaction.atomic() in concurrent environments
- Never call
save() inside pre_save signal — causes infinite recursion; use update_fields
bulk_create skips signals and save() — don't use when signal logic is required
- Migrations on large tables: use
RunSQL with CONCURRENTLY index creation to avoid locks
ORM: select_related vs prefetch_related
books = Book.objects.select_related("author", "author__publisher").all()
authors = Author.objects.prefetch_related("books", "books__tags").all()
from django.db.models import Prefetch
Author.objects.prefetch_related(
Prefetch("books", queryset=Book.objects.filter(published=True), to_attr="active_books")
)
ORM: annotations and aggregations
from django.db.models import Count, Avg, Q, F, Value
django.db.models.functions Coalesce
Author.objects.annotate(
book_count=Count(),
avg_rating=Coalesce(Avg(), Value()),
high_rated=Count(, =Q(books__rating__gte=)),
).(book_count__gt=).order_by()