Odoo 9 - 取决于上下文的动态选择字段

Odoo 9 - Dynamic Selection field depending context

我被这个问题困住了,有人可以帮忙吗? 我想获得 stock.pack.operation 中某个 picking_id 的当前产品列表。 我通过表单视图使用上下文传递 picking_id 。 当我尝试设置选择字段时,我一无所获,但当我尝试使用字符字段时,它起作用了。

代码如下:

def _default_products_list(self):
    active_id = self.env.context.get('default_picking_id', []) or []
    vals=[]
    for record in self.env['stock.pack.operation'].search([('picking_id','=',active_id)]):
        vals.extend([(record.product_id.name,record.product_id.name)])
    return vals

name = fields.Char(string='test', required=True, default=_default_products_list)
product = fields.Selection(_default_products_list, string="Product")

您可以使用 many2one 并添加 filter 以仅显示当前 picking_id:

中的产品
    @api.onchange('picking_id')
    def on_change_picking_id(self):
        """ add domain to product id to show only product that are in the current picking"""
        if self.picking_id:
            # i'm not in my compute i forget how to get list of ids from picking_id
            picking_product_ids = self.picking_id.mapped('move_lines.product_id').ids
            return {'domain': {'product_id': [('id', 'in', picking_product_ids)]}}
        else:
            # remove domain to show all products
            return {'domain': {'product_id': []}}