django-pagination-performance

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Django Pagination Performance

Django 分页性能优化

Use this skill when a Django list view or API slows down as pages get deeper or result sets grow. Pagination is a query-design problem as much as a response-shaping problem.
当Django列表视图或API随着页面深度增加或结果集扩大而变慢时,可使用本方案。分页既是响应格式设计问题,也是查询设计问题。

Workflow

工作流程

  1. Confirm the list contract.
    • Is arbitrary page access required, or only next/previous?
    • Does the UI need a total count?
    • Can ordering be fixed and stable?
    • What page size limit is acceptable?
  2. Measure the current query.
    • Capture SQL for the page query and count query.
    • Check ordering, indexes, and high page numbers.
    • Use
      QuerySet.explain()
      for deep pages.
  3. Choose the pagination style.
    • Use Django
      Paginator
      for moderate result sets and arbitrary page access.
    • Use capped offset pagination when page numbers are useful but deep pages should be limited.
    • Use keyset/cursor pagination for large feeds, timelines, logs, and infinite scroll.
    • Use DRF
      CursorPagination
      for API next/previous navigation with stable ordering.
  4. Make ordering deterministic.
    • Use a unique or nearly unique immutable ordering field.
    • Add a primary-key tie breaker when needed.
    • Ensure the index matches filters plus ordering.
See pagination-patterns.md for Django and DRF examples.
  1. 确认列表约定。
    • 是否需要任意页面访问,还是仅需上一页/下一页?
    • UI是否需要总计数?
    • 排序是否可以固定且稳定?
    • 可接受的页面大小限制是多少?
  2. 评估当前查询。
    • 捕获页面查询和计数查询的SQL语句。
    • 检查排序方式、索引以及高页码的情况。
    • 对深度页面使用
      QuerySet.explain()
      分析。
  3. 选择分页样式。
    • 对于中等规模结果集和任意页面访问需求,使用Django
      Paginator
    • 当页码有用但需限制深度页面时,使用受限偏移分页。
    • 对于大型信息流、时间线、日志和无限滚动场景,使用键集/游标分页。
    • 对于需要稳定排序的API上一页/下一页导航,使用DRF
      CursorPagination
  4. 确保排序确定性。
    • 使用唯一或近乎唯一的不可变排序字段。
    • 必要时添加主键作为平局决胜项。
    • 确保索引与筛选条件及排序方式匹配。
查看pagination-patterns.md获取Django和DRF示例。

Safety Notes

注意事项

  • Deep
    LIMIT/OFFSET
    pages can be slow because the database still walks skipped rows.
  • Unordered querysets produce inconsistent pages.
  • Cursor pagination restricts arbitrary page jumps and user-controlled ordering.
  • Large exact counts can dominate list latency.
  • 深度
    LIMIT/OFFSET
    页面可能较慢,因为数据库仍需遍历跳过的行。
  • 未排序的查询集会导致页面内容不一致。
  • 游标分页限制了任意页面跳转和用户可控的排序方式。
  • 精确的大型计数可能会主导列表的延迟。

Verification

验证步骤

Measure first page, representative deep page, count query, and insertion/deletion consistency for the chosen pagination contract.
针对所选分页约定,测量第一页、典型深度页面、计数查询的性能,以及插入/删除操作的一致性。