根据选择字段更改 Many2one 域

Change Many2one domain based on selection field

我想根据用户在选择字段中的选择更改 M2O 字段域:

  @api.onchange('search_by')
  def _get_partner(self):
        partners  = self.env['customer.regist'].search([('name','!=','New')])
        partner_list = []
        partner_list2 = []
        for rec in partners:
            partner_list.append(rec.name)
            partner_list2.append(rec.phone)
        res = {}
        if self.search_by == 'code':
            res['domain'] = {'search_value': [('name', 'in', partner_list)]}
        if self.search_by == 'phone':
            res['domain'] = {'search_value': [('phone', 'in', partner_list2)]}
        return res

但域未更改并从模型中获取默认域

像这样更改您的函数。

@api.onchange('search_by')
  def _get_partner(self):
        partners  = self.env['customer.regist'].search([('name','!=','New')])
        partner_list = []
        partner_list2 = []
        for rec in partners:
            partner_list.append(rec.name)
            partner_list2.append(rec.phone)
        res = {}
        if self.search_by == 'code':
            domain = {'search_value': [('name', 'in',     partner_list)]}
        return {'domain': domain}
        if self.search_by == 'phone':
            domain = {'search_value': [('phone', 'in', partner_list2)]}
        return {'domain': domain}

尝试这样做:

@api.onchange('search_by')
def _get_partner(self):
    partners  = self.env['customer.regist'].search([('name','!=','New')])
    partner_list = []
    partner_list2 = []
    for rec in partners:
        if rec.name :
            partner_list.append(rec.name)
        if rec.phone:
            partner_list2.append(rec.phone)
    res = {}
    if self.search_by == 'code':
        res['domain'] = {'search_value': [('name', 'in', partner_list)]}
    if self.search_by == 'phone':
        res['domain'] = {'search_value': [('phone', 'in', partner_list2)]}
    return res

确保永远不会将 'False' 值添加到域中,因为它可能会产生无效结果