Odoo-ORM如何从product.template获取翻译后的名称?
获取Odoo product.template翻译后名称的ORM方法
嘿,这个问题我刚好在做多语言电商模块的时候处理过,Odoo里通过ORM获取翻译后的产品名称其实有几种实用的方式,根据你的使用场景来选就行:
1. 基于当前上下文语言自动获取
如果你的代码是在用户请求上下文里运行(比如模型方法、控制器、视图动作),Odoo会自动根据当前用户的语言设置返回翻译后的名称,直接读name字段就好:
# 假设你已经拿到了产品ID product = self.env['product.template'].browse(product_id) # 这里的name会自动返回当前用户语言的翻译值,没有翻译则返回原始名称 translated_name = product.name
2. 指定语言获取翻译(忽略当前上下文)
如果你需要获取某一特定语言的翻译,不管当前用户的语言设置,只需要用with_context()切换上下文的lang参数即可:
# 比如获取西班牙语的翻译 product_es = self.env['product.template'].with_context(lang='es_ES').browse(product_id) spanish_name = product_es.name # 批量获取多个产品的法语翻译 french_products = self.env['product.template'].with_context(lang='fr_FR').search_read( [('active', '=', True)], # 筛选条件 ['name', 'default_code'] # 需要的字段 ) # 提取翻译后的名称列表 french_names = [prod['name'] for prod in french_products]
3. 直接查询翻译记录(进阶场景)
如果需要额外检查翻译是否存在,或者手动处理翻译数据,可以直接查询ir.translation模型(Odoo存储所有翻译的核心模型):
def get_product_translation(self, product_id, lang_code): # 查找对应产品name字段的翻译记录 translation = self.env['ir.translation'].search([ ('name', '=', 'product.template,name'), # 格式:模型名,字段名 ('res_id', '=', product_id), ('lang', '=', lang_code), ('type', '=', 'model') ], limit=1) if translation: return translation.value # 如果没有翻译,返回原始名称 return self.env['product.template'].browse(product_id).name
注意事项
- 确保
product.template的name字段确实设置了translatable=True(Odoo默认是开启的,除非你自定义修改过); - 如果没有对应语言的翻译,Odoo会默认返回产品创建时的原始名称;
- 上述方法在Odoo 12至16版本都经过测试,兼容性没问题。
内容的提问来源于stack exchange,提问作者M.E.
相关产品推荐
相关产品推荐

