在Odoo中,one2many
字段表示一个模型中的记录与另一个模型中的多个记录之间的关系。例如,一个销售订单可能有多个销售订单行。当你需要在添加或编辑one2many
字段时进行计算,你可以使用Odoo的计算字段(computed fields)和onchange方法来实现。
以下是一些步骤和示例代码,帮助你在Odoo中添加或编辑one2many
字段时进行计算:
假设我们有两个模型:sale.order
(销售订单)和sale.order.line
(销售订单行)。
from odoo import models, fields, api
class SaleOrder(models.Model):
_name = 'sale.order'
_description = 'Sale Order'
name = fields.Char(string='Order Reference', required=True)
order_line = fields.One2many('sale.order.line', 'order_id', string='Order Lines')
class SaleOrderLine(models.Model):
_name = 'sale.order.line'
_description = 'Sale Order Line'
order_id = fields.Many2one('sale.order', string='Order Reference', required=True)
product_id = fields.Many2one('product.product', string='Product', required=True)
quantity = fields.Float(string='Quantity', required=True)
price_unit = fields.Float(string='Unit Price', required=True)
subtotal = fields.Float(string='Subtotal', compute='_compute_subtotal')
在上面的SaleOrderLine
模型中,我们添加了一个计算字段subtotal
,它将根据quantity
和price_unit
计算小计。
@api.depends('quantity', 'price_unit')
def _compute_subtotal(self):
for line in self:
line.subtotal = line.quantity * line.price_unit
如果你需要在添加或编辑one2many
字段时进行更复杂的计算或更新其他字段,可以使用onchange
方法。
例如,当用户更改quantity
或price_unit
时,我们可能希望自动更新subtotal
并计算整个订单的总金额。
@api.onchange('order_line')
def _onchange_order_line(self):
total_amount = sum(line.subtotal for line in self.order_line)
self.total_amount = total_amount
在SaleOrder
模型中添加total_amount
字段:
total_amount = fields.Float(string='Total Amount', compute='_compute_total_amount')
@api.depends('order_line.subtotal')
def _compute_total_amount(self):
for order in self:
order.total_amount = sum(line.subtotal for line in order.order_line)
确保你的视图(XML)中包含了这些字段,并且正确设置了关系。
<record id="view_order_form" model="ir.ui.view">
<field name="name">sale.order.form</field>
<field name="model">sale.order</field>
<field name="arch" type="xml">
<form string="Sale Order">
<sheet>
<group>
<field name="name"/>
<field name="total_amount" readonly="1"/>
</group>
<notebook>
<page string="Order Lines">
<field name="order_line">
<tree string="Order Lines">
<field name="product_id"/>
<field name="quantity"/>
<field name="price_unit"/>
<field name="subtotal" readonly="1"/>
</tree>
</field>
</page>
</notebook>
</sheet>
</form>
</field>
</record>
通过这些步骤,你可以在Odoo中实现one2many
字段的添加或编辑时的计算功能。确保你的计算字段和onchange方法正确处理了所有必要的业务逻辑。
领取专属 10元无门槛券
手把手带您无忧上云