odoo - 如何在创建函数中使用 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)
但这在我的情况下不起作用..
谢谢您的帮助!
解决方案
终于想通了。有一些隐藏的陷阱:
- self.onchange 实际上调用了@api.depends 和@api.onchange 修饰函数
- values dict(self.onchange 的第一个参数)实际上有 2 种用途:检查下面的代码
- (观察)self.onchange返回值dict,不包括未被通过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
推荐阅读
- java - 如何在Java中的一个类中调用另一个类的方法
- c# - 实体框架用户定义查询条件
- python-3.x - Geopandas 126:找不到指定的模块
- azure - 存储帐户 -- 导出 blob 大小和日期
- javascript - 如何避免在 javascript 中为 document.location.href 命令编写跨站点脚本
- flutter - 由于 googleusercontent.com 上的互联网限制,flutter web 无法正常工作
- sorting - 我如何以编程方式知道经典报告中的排序顺序是什么?
- javascript - 使用 React-Router-Dom,有没有办法在事件/函数调用上重定向页面,而不是使用和需要按下按钮?
- bash - 获取域的 SSL 到期日期的脚本
- angular - 从 ts 文件手动设置值时,ngModel 不起作用