---
name: "django-orm-select-related-prefetch"
description: "Eliminate N+1 database queries and optimize heavy relational data loading in Django ORM."
metadata:
  author: "Django"
  version: "1.0.0"
  runtime_compatibility:
    - "codex"
    - "claude-code"
    - "cursor"
    - "windsurf"
triggers:
  - "fix n+1 query django orm"
  - "select_related vs prefetch_related"
  - "django orm only defer"
permissions:
  fs_read: true
  fs_write: "workspace"
  shell_exec: false
  net_access: false
---

# Django ORM Query Optimization & N+1 Prevention

Optimizes Django ORM queries: using select_related for single foreign keys (SQL JOIN), prefetch_related with Prefetch objects for many-to-many, only() and defer(), and profiling queries with django-debug-toolbar.

## When to Invoke
Invoke this skill whenever you need to:
- fix n+1 query django orm
- select_related vs prefetch_related
- django orm only defer

## Execution SOP & Rules
1. Use select_related('author', 'category') for one-to-one and foreign key relationships.
2. Use prefetch_related('tags', 'comments') for reverse foreign keys and many-to-many relationships.
3. Filter related querysets: prefetch_related(Prefetch('orders', queryset=Order.objects.filter(status='paid'))).
4. Audit SQL statements using connection.queries or Django Debug Toolbar to confirm query count stays constant.

## Verification Checklist
- Run local linting, syntax validation, and type-checks before reporting completion.
- Ensure all created or modified files adhere to workspace boundaries and avoid uncommitted secrets.
- Verify tests or build commands exit cleanly with return code 0.
