如何在create函数中使用odoo的服务器端onchange方法?

问题描述

例如,如果要触发此功能

@api.onchange("fieldA")
def _onchange(self):
   for rec in self:
        random = rec.fieldB

onchange函数通常采用以下形式:onchange(values,field_name,field_onchange)

子问题1:我要求fieldB已经可用。是否将其传递给“值”参数?
子问题2:回答者能否提供适当的代码示例?


参考文献中给出的常见示例通常采用以下形式:

wizard = self.env['library.return.wizard']
values = {'borrower_id': self.env.user.partner_id.id}
specs = wizard._onchange_spec()
updates = wizard.onchange(values,['borrower_id'],specs)
....
....
wiz = wizard.create(values)

但这对我来说不起作用

感谢您的帮助!

解决方法

最后弄清楚了。有一些隐藏的陷阱:

  1. self.onchange实际上同时调用@ api.depends和@ api.onchange装饰函数
  2. values dict(self.onchange的第一个参数)实际上有2种用途:请在下面检查我的代码
  3. (观察)self.onchange返回值字典,不包括通过self.onchange调用的功能修改的字段

您可以在下面参考我的代码注释以获取更多详细信息。 希望这对某人有帮助。

 @api.model
    def create(self,vals):
        # SECTION: Trigger server-side onchange to initialize all child dependent values of qty_to_ship. More generally,to trigger all @api.onchange functions in this shipment.item model.
        
        stock_move = self.env['stock.move'].browse([vals['move_id']])
        # 'values' dict: (1) provide values of fields when used in calling onchange functions (2) indicate fields that we want a return value for after calling onchange
        # Note: some key-values are commented because related fields of move_id will be computed when we call self.onchange
        values = {
            # 'product_id': stock_move.product_id.id,# 'product_tmpl_id': stock_move.product_id.product_tmpl_id.id,'move_id': stock_move.id,'qty_to_ship': stock_move.product_uom_qty,'carton_qty': 0,'item_sub_total': 0,}
        specs = self._onchange_spec()
        # Note: self.onchange,triggers both @api.depends,@api.onchange decorated functions (this is not mentioned in any documentation)
        # Note: the order of the list (2nd arg) matters
        # move_id needed to: trigger def _assign_relational_fields
        # product_tmpl_id needed to: trigger def _compute_carton_single
        # qty_to_ship needed to: trigger other functions with @api.onchange('qty_to_ship') decorator
        updates = self.onchange(values,['move_id','product_tmpl_id','qty_to_ship'],specs)
        value = updates.get('value',{}) 
        for name,val in value.items(): 
            if isinstance(val,tuple): 
                value[name] = val[0]
        vals.update(value)
        # insert qty_to_ship as it is not modified by any of the onchange functions triggered earlier. Hence it will not be attached to 'value' dict
        vals.update({'qty_to_ship': stock_move.product_uom_qty})

        # Continue with super create
        res = super(ACDShipmentItems,self).create(vals)

        return res