在odoo中inverse
时间: 2025-04-24 14:32:53 浏览: 26
### Odoo 中 `inverse` 属性的用法
在 Odoo 的模型定义中,字段可以带有不同的属性来控制其行为。其中 `inverse` 是一种用于双向关系管理的重要属性。
#### 定义与作用
当创建一个关联两个模型的关系字段(如 one2many 或 many2one)时,通常会有一个对应的反向字段。这个反向字段通过设置 `inverse` 参数指定如何更新另一端的数据[^1]。
例如,在订单项和产品之间建立联系时:
```python
class Order(models.Model):
_name = 'order'
line_ids = fields.One2many('order.line', 'order_id', string='Order Lines')
class OrderLine(models.Model):
_name = 'order.line'
order_id = fields.Many2one('order', ondelete='cascade')
product_id = fields.Many2one('product.product', required=True)
quantity = fields.Float(default=1)
@api.depends('quantity')
def _compute_total(self):
for record in self:
record.total = record.quantity * (record.price or 0.0)
total = fields.Monetary(compute='_compute_total', store=True, currency_field='currency_id')
```
在这个例子中,如果想要修改父对象中的某些数据并同步到子对象,则可以在子对象上定义计算字段或方法,并利用 `@api.onchange()` 装饰器实现即时反馈;而为了能够从子表单保存更改回溯影响主记录,则需要用到 `inverse` 方法。
对于上述代码片段而言,假设现在希望每当调整了某个订单行的数量 (`quantity`) 后自动重新计算整个订单总额(`total_amount`) ,那么就可以这样做:
```python
class Order(models.Model):
...
total_amount = fields.Float(string="Total Amount", compute="_compute_total_amount", inverse="_set_line_quantities")
def _compute_total_amount(self):
"""Compute the sum of all lines."""
for rec in self:
rec.total_amount = sum(rec.mapped('line_ids.subtotal'))
def _set_line_quantities(self):
"""Set quantities based on new total amount value"""
for rec in self.filtered(lambda r: r.total_amount != sum(r.mapped('line_ids.subtotal'))):
avg_price_per_unit = rec.total_amount / len(rec.line_ids) if rec.line_ids else 0
for line in rec.line_ids:
line.write({'price': avg_price_per_unit})
```
这里的关键在于 `_set_line_quantities` 函数作为 `inverse` 处理程序被调用来响应用户对总金额的手动编辑操作。这使得即使是在视图层面改变了汇总值之后也能保持内部一致性。
阅读全文
相关推荐

















