python - 如何在 create() 函数中获取动态 many2many 字段的值
问题描述
我想从 create() 函数中动态填充的 many2many 字段中获取值,但是我得到了这个结果 [[6, False, [98]]], 98 实际上是预期的结果,尽管这是我下面的代码
class CustomTransRequest(models.Model):
_name = 'custom.trans.request'
_description = 'Transfer Request'
branch_from_id = fields.Many2one('custom.branch', string="From", required=True)
branch_to_id = fields.Many2one('custom.branch', string="To", required=True)
line_id = fields.Many2one('custom.branch.line', string="Products", required=True)
product_id = fields.Many2many('custom.product', required=False, )
qty = fields.Integer(string="Qty", required=True)
@api.onchange('line_id')
def onchange_line(self):
if self.line_id:
for rec in self:
selected_products = rec.env['custom.branch.line'].search(
[('id', '=', rec.line_id.id)]).mapped('product_id')
self.product_id = [(6, 0, selected_products.ids)]
@api.model
def create(self, vals):
print("Create Function ")
print("SELECT id FROM custom_branch_line WHERE (branch_id = %s) AND (product_id = %s)" % (
vals.get('branch_to_id'), vals['product_id']))
result = super(CustomTransRequest, self).create(vals)
return result
解决方案
这就是 Odoo 处理 X2many 字段的方式,按照惯例,大多数时候在 create 方法中它们被称为命令(或命令列表),将为您的 m2m 字段传递的命令将是:
# only one command 6 which tell Odoo replace all record with the selected ids
[(6, 0, [list_of_selected_record_ids)]
因此,为了检索它们,只需执行以下操作:vals['product_id'][0][2]
不,我不知道您是只是想显示选择查询还是要使用,如果您只是打印它:
# replace vals['product_id'] with
'({})'.format(','.join(vals['product_id'][0][2]))
如果要执行它,请使用查询参数:
self.cr.execute("SELECT id FROM custom_branch_line WHERE (branch_id = %s) AND (product_id = %s)", (vals['branch_to_id'], vals['product_id'][0][2]))
有关 X2many 命令的更多信息,请查看:
One2many 和 Many2many 使用特殊的“命令”
注意:我假设此字段不会为空,否则您需要先检查字段是否为空。
推荐阅读
- ios - 使用xcode获取iphone应用程序视图中的所有元素
- android - 为多个选项卡重用膨胀视图
- javascript - 如何修复 Javascript 中的“未定义不是对象”错误
- python - form.as_hidden 不将值传递给 POST
- shell - 通过运行shell脚本设置环境后如何执行命令?
- c++ - 如何使用来自GPIO的定时器中断通过c ++代码控制BeagleBone Black中ADC的采样周期?
- node.js - 开玩笑无法从“client.js”中找到模块“pg-native”
- javascript - 如何在 ForceDirectedTree amcharts 中的气泡上添加自定义事件
- google-analytics - gtag 事件购买货币被忽略,始终为美元
- core-data - Xcode中核心数据内置持久化存储类型的默认方法