django-orm-query-optimization
Optimize Django ORM query loading by fixing N+1 queries, duplicate related-object queries, over-fetching, serializer/template query loops, and inappropriate select_related, prefetch_related, only, or defer usage. Use when a Django page, API, admin view, template, serializer, or queryset issues too many queries or loads more model data than needed.
- License 许可
- MIT
- 最近更新
- 2026-11-14
- Stars
- ★ 1.6k
- Forks
- 491
01 前言 Front Matter
- name
- django-orm-query-optimization
- license
- MIT
- metadata
- { "tags": "django,orm,querysets,performance,n-plus-one", "version": "0.1.0", "category": "Django", "displayName": "Django ORM Query Optimization" }
- description
- Optimize Django ORM query loading by fixing N+1 queries, duplicate related-object queries, over-fetching, serializer/template query loops, and inappropriate select_related, prefetch_related, only, or defer usage. Use when a Django page, API, admin view, template, serializer, or queryset issues too many queries or loads more model data than needed.
- compatibility
- Codex, Claude Code, and other Agent Skills-compatible clients.
02 资源文件 1
03 SKILL.md 正文
Django ORM Query Optimization
Use this skill for query-count and object-loading problems. The usual target is an N+1 pattern where each rendered row or serialized object triggers more database work.
Workflow
-
Prove the query pattern.
- Capture query count and duplicate SQL for the slow path.
- Identify the loop, serializer field, template access, admin display, or model property triggering related queries.
-
Choose the loading strategy.
- Use
select_related()for single-valued relationships:ForeignKeyandOneToOneField. - Use
prefetch_related()for many-valued relationships: reverse FK and many-to-many. - Use
Prefetch()when the related queryset needs filters, ordering, annotations, or nestedselect_related(). - Use
values()orvalues_list()when model instances are unnecessary. - Use
only()ordefer()only when large columns are truly unused.
- Use
-
Keep access consistent.
- If you prefetch
items, do not later callitems.filter(...)and expect the prefetch cache to help. - If using
iterator()withprefetch_related(), providechunk_size. - Avoid putting broad prefetches into default managers unless every caller needs them.
- If you prefetch
-
Add a focused regression check when useful.
- Use a query-count assertion around the exact view or serializer path.
- Avoid brittle global query-count tests.
See relationship-and-column-loading.md for examples and review cues.
Anti-Patterns
- Adding
prefetch_related()to every queryset without checking memory. - Using
only()and then touching deferred fields in a loop. - Optimizing a queryset but leaving serializer method fields to issue per-row queries.
- Hiding queries in
__str__(), model properties, template includes, or admin list methods.
Verification
Show the query count and duplicate-query pattern before and after, plus any wall-time or memory change.
04 同仓库更多 Skills
worktable-review-with-annotations
Create, inspect, reply to, update, or resolve situated Worktable annotations. Use when feedback belongs to a Doc section, block, text range, or HTML Doc, or when the user asks to address existing review feedback and coordinate a requested artifact edit.
worktable-find-and-synthesize-context
Find, assess, and synthesize context from Worktable Docs and Records. Use when the user asks what a workspace contains, wants workspace-backed research, needs current facts reconciled across artifacts, or requests a cited synthesis without changing workspace state.
worktable-create-or-update-docs
Create, edit, rename, or maintain narrative Worktable Docs. Use for plans, decisions, briefs, notes, research syntheses, and other durable prose when the user requests a new artifact or a safe update to an existing one.
worktable-create-or-manage-records
Organize repeated structured information as durable Worktable Records. Use for research datasets, inventories, directories, pipelines, trackers, and other collections whose items need identity, fields, filtering, links, validation, or individual updates.
worktable-create-or-manage-interactive-html
Create or improve durable visual and interactive artifacts in Worktable. Use for dashboards, trackers, calculators, mini apps, slide presentations, and other requests that benefit from a polished HTML Doc.
worktable-collaborate-threads
Read, answer, and hand off messages through durable Worktable threads with users or other authenticated participants. Use when the user asks to check addressed messages, reply to a participant, continue a thread, request another agent's help, wait briefly for a response, or watch for comments and messages sent to the agent.