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

Flask使用Pagination时无法找到items属性,如何获取分页数据?

问题原因

你使用的是flask-paginate扩展的Pagination类,这个类的定位是仅处理分页逻辑计算、生成分页前端导航代码,本身不承载分页后的数据集,所以确实没有items属性。你需要根据它计算好的偏移量手动对原始列表做切片,获取当前页的展示数据。

解决方法

Pagination实例已经提供了skip属性,值为当前页需要跳过的记录总数,你直接用这个值对原始列表做切片即可:

# 计算当前页对应的数据切片
current_page_items = campaign_brief_result[paginated_data.skip : paginated_data.skip + paginated_data.per_page]

current_page_items就是你要的分页后数据,直接遍历它做展示即可。

完整可运行示例

from flask_paginate import Pagination

# 原始数据
campaign_brief_result = [
    {'id': 112233, 'name': 'DSR-335', 'description': 'Desc', 'currency': '0'},
    {'id': 11223344, 'name': 'DSR-336', 'description': 'Desc2', 'currency': '2'},
    {'id': 11223345, 'name': 'DSR-337', 'description': 'Desc3', 'currency': '1'},
    {'id': 11223346, 'name': 'DSR-338', 'description': 'Desc4', 'currency': '0'},
]

page = 2 # 假设要访问第2页
per_page = 2 # 每页2条
paginated_data = Pagination(
    page = page,
    per_page = per_page,
    total = len(campaign_brief_result),
    search = False,
    record_name = 'campaign_brief_result'
)

# 获取当前页数据
current_page_items = campaign_brief_result[paginated_data.skip : paginated_data.skip + paginated_data.per_page]
print(current_page_items)
# 输出结果为第2页的2条数据:[{'id': 11223345, 'name': 'DSR-337', 'description': 'Desc3', 'currency': '1'}, {'id': 11223346, 'name': 'DSR-338', 'description': 'Desc4', 'currency': '0'}]

如果是在Flask视图中使用,只需要把current_page_items和paginated_data同时传递到模板中,遍历current_page_items渲染数据列表,调用paginated_data.links()渲染分页导航条即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 17:57:01