You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在Django Rest Framework中实现基于limit与page_no的自定义分页

自定义分页实现方案

核心逻辑

根据传入的page_no计算偏移量offset,公式为:
offset = (page_no - 1) * 每页条数
这里每页固定显示10条数据,因此直接套用(page_no - 1) * 10即可满足需求。

完整实现代码

# 从请求中获取page_no参数,未传参时默认返回第1页
page_no = request.GET.get('page_no', 1)
try:
    page_no = int(page_no)
    # 确保页码不小于1,避免无效页码引发查询错误
    page_no = max(page_no, 1)
except ValueError:
    # 若传入非数字格式的页码,默认返回第1页
    page_no = 1

# 定义每页显示的数据条数
PAGE_SIZE = 10
offset = (page_no - 1) * PAGE_SIZE

# 带动态分页的查询语句
get_queryset = Comments.objects.filter(
    language_post_id=post_in_lang_id,
    is_post_comment=True
).order_by('-created_on')[offset:offset+PAGE_SIZE]

关键说明

  • 兼容无page_no参数的场景,默认返回第一页数据
  • 增加参数合法性校验,避免传入非数字页码导致程序报错
  • 强制页码最小值为1,防止计算出负数偏移量引发查询异常

内容的提问来源于stack exchange,提问作者MdHassan413

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 05:15:33