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

Odoo开发中如何在search查询时对default_code执行trim去除末尾空格

Odoo search查询对default_code字段执行trim操作的解决方法

你需要的是去除数据库中default_code字段的末尾空格后再匹配查询值,Odoo ORM原生domain不支持直接对字段应用字符串处理函数,可根据你的数据量选择以下两种方案:

方案1:小数据量场景(实现最简单)

先通过模糊匹配缩小查询范围,再在内存中做trim后过滤:

# 先预处理查询值
target_code = fs_product['id'].strip()
# 模糊匹配缩小候选集,减少内存占用
candidate_products = self.search([('default_code', 'ilike', target_code)])
# 内存中对default_code做右侧去空格后匹配,取第一条
product_id = candidate_products.filtered(lambda p: p.default_code.rstrip() == target_code)[:1]

方案2:大数据量场景(性能更高)

直接使用原生SQL调用PostgreSQL的rtrim函数处理字段,避免加载大量数据到内存:

target_code = fs_product['id'].strip()
self.env.cr.execute("""
    SELECT id FROM product_product 
    WHERE rtrim(default_code) = %s
    LIMIT 1
""", (target_code,))
result = self.env.cr.fetchone()
# 转成Odoo记录集
product_id = self.browse(result[0]) if result else self.env['product.product']

特殊情况处理

如果是你传入的fs_product['id']本身带首尾空格,不需要修改匹配逻辑,直接预处理查询值即可:

target_code = fs_product['id'].strip()
product_id = self.search([('default_code','=', target_code)], limit=1)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 05:45:02