Odoo 16自定义网站搜索结果分页异常问题求助
Odoo搜索分页问题修复:页码异常+点击页码加载全部数据
问题根源分析
- 总记录数计算错误:你用
search_count([])获取总数量,这会返回所有客户的总数,而非搜索后的结果数,导致分页组件生成全部页码。 - 分页逻辑低效且易出错:先查询所有符合条件的记录再切片,不仅性能差,还会在搜索参数丢失时加载全量数据;同时
step=3和切片的+5不一致,每页显示数量混乱。 - 分页链接丢失搜索参数:Pager的URL未携带
search参数,点击页码时搜索条件直接丢失,回到全量数据状态。 - 表单提交方式不匹配:搜索表单用POST提交,但分页是GET请求,参数传递方式冲突,导致分页无法保留搜索关键词。
修复后的控制器代码
class MyCustomWeb(http.Controller): @http.route(['/customer', '/customer/page/<int:page>'], type="http", auth="user", website=True) def customer_kanban(self, page=1, search=None, **post): domain = [] if search: domain.append(('name', 'ilike', search)) # 计算搜索结果的总记录数 total = request.env['res.partner'].sudo().search_count(domain) # 统一每页显示5条数据 step = 5 pager = request.website.pager( url='/customer', url_args={'search': search}, # 给分页链接带上搜索参数 total=total, page=page, step=step, ) # 直接在数据库层面做分页,避免加载全部数据 customer_obj = request.env['res.partner'].sudo().search( domain, offset=pager['offset'], limit=step ) return request.render('my_module.customer_form', { 'search': search, 'customer_details': customer_obj, 'pager': pager, })
修复后的XML模板代码
<template id="customer_form" name="Customers"> <t t-call="website.layout"> <div> <div class="col-md-6"> <br/> <div> <!-- 改成GET提交,让搜索参数出现在URL中,方便分页携带 --> <form action="/customer" method="get"> <t t-call="website.website_search_box"> </t> <input type="hidden" name="csrf_token" t-att-value="request.csrf_token()"/> <div> <section> <div class="customer_details"> <center> <h3>Customers</h3> </center> </div> <br/> <div class="oe_product_cart_new row" style="overflow: hidden;"> <t t-foreach="customer_details" t-as="customers"> <div class="col-md-3 col-sm-3 col-xs-12" style="padding:1px 1px 1px 1px;"> <div style="border: 1px solid #f0eaea;width: 150px;height: auto;padding: 7% 0% 10% 0%; border-radius: 3px;overflow: hidden; margin-bottom: 44px !important;width: 100%;height: 100%;"> <div class="oe_product_image"> <center> <div style="width:100%;overflow: hidden;"> <img t-if="customers.image_1920" t-attf-src="/web/image/res.partner/#{customers.id}/image_1920" class="img oe_product_image" style="padding: 0px; margin: 0px; width:auto; height:100%;"/> </div> <div style="text-align: left;margin: 10px 15px 3px 15px;"> <t t-if="customers.name"> <span t-esc="customers.name" style="font-weight: bolder;color: #3e3b3b;"/> <br/> </t> </div> </center> </div> </div> </div> </t> </div> <div class="products_pager form-inline justify-content-center mt-3"> <t t-call="website.pager"> <t t-set="_classes">mt-2 ml-md-2</t> </t> </div> </section> <br/> <hr class="border-600 s_hr_1px w-100 mx-auto s_hr_dotted"/> </div> </form> </div> </div> </div> </t> </template>
关键修复说明
- 总记录数修正:基于当前搜索的
domain计算总数量,确保分页页码对应搜索结果的实际页数。 - 数据库级分页:通过
search方法的offset和limit参数直接获取当前页数据,避免一次性加载全量记录。 - 分页携带搜索参数:在
pager中添加url_args传递搜索关键词,让分页链接自动保留搜索条件。 - 表单改为GET提交:使搜索参数出现在URL中,和分页的GET请求兼容,保证分页时搜索条件不丢失。
- 统一每页数量:将
step和limit设为相同值,确保每页显示数据数量一致。
内容的提问来源于stack exchange,提问作者K.ju
相关产品推荐
相关产品推荐

