如何在Odoo 17中访问翻译值并在QWeb报表中调用?
在Odoo QWeb报表中同时展示字段原值与翻译值的解决方案
问题回顾
我在Odoo中创建了包含带翻译功能字段的表单,用户已录入翻译值,需在QWeb报表中调用这些值,能否生成同时包含原值与翻译值的QWeb报表?
我尝试编写函数获取翻译值,但在QWeb报表中无法识别,使用的函数如下:
def generate_report(self): # Retrieve records records = self.search([]) # Prepare data for the report report_data = [] for record in records: # Retrieve translated values of fields trans_nom = record.with_context(lang='ar').nom trans_prenom = record.with_context(lang='ar').prenom trans_lieu_realisation = record.with_context(lang='ar').lieu_realisation trans_decision_conseil = record.with_context(lang='ar').decision_conseil # Append data to report_data list report_data.append({ 'trans_nom': trans_nom, 'trans_prenom': trans_prenom, 'trans_lieu_realisation': trans_lieu_realisation, 'trans_decision_conseil': trans_decision_conseil }) # Render the Qwebreport with the data report = self.env.ref('acces.imprimer_fiche_etudiant_action').render({ 'docs': report_data, }) return report我还通过if-else语句排查,确认其他功能正常,仅翻译值无法被识别,恳请各位提供解决思路或方案。
问题分析
你的代码核心问题有两个:
- 仅传递了翻译值,未保留原值;且直接将字段对象存入字典时,Odoo的字段代理特性可能导致翻译值未被正确解析为字符串
- 渲染报表时的上下文可能覆盖了你设置的语言上下文,导致翻译值失效
解决步骤
1. 修改报表生成函数,同时传递原值与翻译值
调整函数,同时保留原始字段值和指定语言的翻译值,并且强制将翻译值转换为字符串,避免字段对象未被解析:
def generate_report(self): records = self.search([]) report_data = [] for record in records: # 保存字段原值 original_data = { 'nom': record.nom, 'prenom': record.prenom, 'lieu_realisation': record.lieu_realisation, 'decision_conseil': record.decision_conseil } # 切换到阿拉伯语上下文,获取翻译值并转为字符串 ar_context = record.with_context(lang='ar') translated_data = { 'trans_nom': str(ar_context.nom) if ar_context.nom else '', 'trans_prenom': str(ar_context.prenom) if ar_context.prenom else '', 'trans_lieu_realisation': str(ar_context.lieu_realisation) if ar_context.lieu_realisation else '', 'trans_decision_conseil': str(ar_context.decision_conseil) if ar_context.decision_conseil else '' } # 合并原值与翻译值,传入报表 report_data.append({**original_data, **translated_data}) report = self.env.ref('acces.imprimer_fiche_etudiant_action').render({ 'docs': report_data, }) return report
2. 调整QWeb模板的字段引用
确保模板中正确调用传递的原值和翻译值,示例如下:
<t t-foreach="docs" t-as="doc"> <div class="student-section"> <h4>原始内容</h4> <p>姓名: <span t-esc="doc.nom"/> <span t-esc="doc.prenom"/></p> <p>执行地点: <span t-esc="doc.lieu_realisation"/></p> <p>委员会决议: <span t-esc="doc.decision_conseil"/></p> <h4>阿拉伯语翻译</h4> <p>姓名: <span t-esc="doc.trans_nom"/> <span t-esc="doc.trans_prenom"/></p> <p>执行地点: <span t-esc="doc.trans_lieu_realisation"/></p> <p>委员会决议: <span t-esc="doc.trans_decision_conseil"/></p> </div> </t>
3. 额外排查点
- 确认阿拉伯语(
ar)已在Odoo系统中启用,且对应字段确实录入了该语言的翻译值 - 检查字段定义是否开启了翻译属性,示例:
nom = fields.Char(string="Nom", translate=True) - 在函数中添加打印语句,确认
ar_context.nom能获取到正确的翻译内容,排除数据录入问题
内容的提问来源于stack exchange,提问作者Kaoutar
相关产品推荐
相关产品推荐

