如何在Odoo 14的发票中获取并打印产品属性值
问题原因
你调用的t-field="l.product_template_attribute_value_ids"、l.full_product_name默认不属于Odoo的account.move.line(发票行)模型字段:前者是product.template/product.product(产品模板/产品)模型的原生字段,后者一般是sale.order.line(销售订单行)的计算字段,所以直接调用会报字段不存在错误。
实现方案
根据使用场景可以选择以下两种方案实现:
方案1:直接在QWeb打印模板中通过关联字段取值(无需新增模型字段)
只要发票行关联了对应产品,就可以直接通过层级关联在QWeb模板中取数,不需要修改底层模型:
- 仅打印产品属性值写法:
<t t-foreach="l.product_id.product_template_attribute_value_ids" t-as="attr"> <span t-esc="attr.name"/><t t-if="not attr_last">、</t> </t>
- 拼接产品名+属性值写法:
<span t-esc="l.product_id.name"/> <t t-if="l.product_id.product_template_attribute_value_ids"> (<t t-foreach="l.product_id.product_template_attribute_value_ids" t-as="attr"> <span t-esc="attr.name"/><t t-if="not attr_last">、</t> </t>) </t>
- 若是销售订单生成的发票,订单行有自定义属性和产品默认属性不一致的情况,可以直接关联销售订单行取完整产品名:
<t t-if="l.sale_line_ids"> <span t-esc="l.sale_line_ids[0].full_product_name"/> </t>
方案2:扩展account.move.line模型新增对应字段(适合多处调用的场景)
如果多个报表、业务视图都需要用到该字段,建议直接扩展模型新增计算字段,步骤如下:
- 继承
account.move.line模型,新增对应计算字段:
from odoo import models, fields, api class AccountMoveLine(models.Model): _inherit = 'account.move.line' full_product_name = fields.Char(string='完整产品名', compute='_compute_full_product_name') product_attribute_values = fields.Char(string='产品属性', compute='_compute_full_product_name') @api.depends('product_id', 'sale_line_ids') def _compute_full_product_name(self): for line in self: # 优先取销售订单行的完整产品名及自定义属性 if line.sale_line_ids: sale_line = line.sale_line_ids[0] line.full_product_name = sale_line.full_product_name attrs = sale_line.product_template_attribute_value_ids.mapped('name') line.product_attribute_values = '、'.join(attrs) else: # 无关联销售订单时直接从产品模型取数 line.full_product_name = line.product_id.name attrs = line.product_id.product_template_attribute_value_ids.mapped('name') line.product_attribute_values = '、'.join(attrs) if attrs else ''
- 字段新增完成后,在QWeb模板中即可直接调用
t-field="l.full_product_name"或t-field="l.product_attribute_values"。
注意事项
- 修改QWeb模板或者继承模型后,需要升级对应自定义模块才会生效
- 多语言场景下需要给新增字段设置
translate=True属性,保证多语言正常显示
内容的提问来源于stack exchange,提问作者ageskill
相关产品推荐
相关产品推荐

