跳到主要内容
知仓学习社ZHICANG

django-db-side-computation

Move Django performance-sensitive Python loops into database-side computation with annotations, aggregates, filtered aggregates, F expressions, func…

不碰外部(只输出文字)无严重或高危命中hashgraph-online/awesome-codex-plugins

它会碰到什么

扫了多少2 个文本文件,5 KB
它会碰到什么不碰外部(只输出文字)
命中总数0 处
命中统计严重 0 · 高 0 · 中 0 · 低 0

这一栏是扫描器报的事实,不是结论。命中多不等于有毒(安全工具、规则库、示例脚本本来就会包含危险写法),命中少也不等于干净。它和你手上的凭据、文件、网络有什么关系,需要你自己看。

技能内容

Django DB-Side Computation

Use this skill when Django fetches rows into Python to compute values the database can compute more efficiently or more consistently.

Workflow

  1. Identify the Python computation.
  • Counts, sums, min/max, booleans, latest related rows, rankings, denormalized totals, or per-row derived fields.
  • Confirm whether the computed value must be exact, current, and transactionally consistent.
  1. Pick the SQL expression level.
  • filter(), exclude(), and F() for simple comparisons and updates.
  • annotate() and aggregates for per-object counts and totals.
  • Filtered aggregates for conditional counts and sums.
  • Exists() for yes/no related-row checks.
  • Subquery() with OuterRef() for latest or scalar related values.
  • Window() for ranks and running calculations.
  • GeneratedField for deterministic same-row computed columns when the database supports it.
  1. Validate query shape.
  • Inspect generated SQL or QuerySet.explain().
  • Clear unintended ordering before grouping when needed.
  • Confirm indexes support joins, filters, and ordering.
  1. Decide whether the result should be stored.
  • Use annotations for request-time values.
  • Use generated fields for same-row deterministic values.
  • Use materialized views or denormalized tables when cross-row aggregate queries are too expensive and can be stale.

See [aggregation-patterns.md](references/aggregation-patterns.md) for Django expression examples.

Safety Notes

  • Database computation is not always faster; complex queries can overload the database or block OLTP work.
  • Generated fields have database-specific restrictions and PostgreSQL supports only persisted generated columns.
  • Subqueries and annotations can duplicate work if composed carelessly. Read the plan.

Verification

Compare correctness against the old Python calculation on representative data, then measure SQL time and total response time.

想直接用这个技能?

本站把开放许可(MIT / Apache 等)的技能按仓库打包整理到网盘,点一下转存到你自己的网盘,不用一个个从 GitHub 拉。许可未声明的技能只给原始仓库链接,不打包。