如何扩展搜索记录以查看自定义 Many2Many 字段?

问题描述

在此图像中,有一条产品搜索记录将搜索 namedefault_code。我需要让它也能查看我的自定义 Many2Many 字段。

Search Product

这是继承模型中的字段。

product_list = fields.Many2many("product.list",string="Product List")

自定义模型只有 _name、_description 和 name 变量。

问题是如何使搜索同时查看该字段的所有可能的 Many2Many 数据。

我在继承模型中尝试过这个:

@api.model
def name_search(self,name='',args=None,operator='ilike',limit=100):
    res = super(product_template_inherit,self).name_search(name='',limit=100)
    ids = self.search(args + [(name,'in','product_list.name')],limit=limit)
    if ids:
        return ids.name_get()
    return res

搜索没有任何反应。不管上面的代码如何,它仍然使用相同的行为进行搜索

总结:我需要能够按产品列表搜索产品(在 product.template 模型中继承的自定义 Many2Many 字段)

==============================================>

更新

我一直在尝试的当前代码现在是这个。

@api.model
def _name_search(self,name,limit=100,name_get_uid=None):
    args = args or []
    if operator == 'ilike' and not (name or '').strip():
        domain = []
    else:
        domain = ['|',('name','ilike',name),('product_list.name',name)]
        product_ids = self._search(expression.AND([domain,args]),limit=limit,access_rights_uid=name_get_uid)
    return self.browse(product_ids).name_get()

但是,它看起来仍然使用相同的旧字段进行搜索。它不会随着我的函数的编写而改变。

解决方法

您可以计算搜索域,然后返回 _search 方法的结果。

fleet 模块已经使用相同的逻辑来使用驾驶员姓名搜索车辆,您只需将 driver_id 替换为 product_list

class ProductProduct(models.Model):
    _inherit = 'product.product'

    @api.model
    def _name_search(self,name,args=None,operator='ilike',limit=100,name_get_uid=None):
        args = args or []
        if operator == 'ilike' and not (name or '').strip():
            domain = []
        else:
            domain = ['|',('name',operator,name),('product_list.name',name)]
        return self._search(expression.AND([domain,args]),limit=limit,access_rights_uid=name_get_uid)