首页 文章

如何通过Odoo中的计算字段进行搜索?

提问于
浏览
2

我正在尝试通过Odoo 9中的计算字段进行搜索 . 但它会返回所有记录作为结果 .

class Version(models.Model):
    _name='product_cars_application.version'

    name = fields.Char(compute="_get_name", store=True)

    @api.one
    def _get_name(self):
        self.name = "%s %s %s (%s)" % (self.brand_id,
                                       self.model_id.name,
                                       self.vname,
                                       self.year_id)

我已尝试使用 store=True 而没有它,但名称字段未存储在数据库中 . 我也尝试从数据库中删除列"name",然后我更新了模块,但它没有存储计算 . 计算字段在表单视图上正常工作,但不存储名称,并且搜索不起作用 .

那么,我如何通过字段名称进行搜索?

2 回答

  • 0

    将其添加到您的代码中 .

    def _name_search(self,name, args=None, operator='ilike', limit=100):
        if operator == 'like': 
           operator = 'ilike'
    
        versions=self.search([('name', operator, name)], limit=limit)
        return versions.name_get()
    
     name = fields.Char(compute=_get_name, store=True,search=_name_search)
    

    您可以在文档中查看详细信息 .

    https://www.odoo.com/documentation/8.0/reference/orm.html

    “计算字段”部分适合您 .

    希望它能奏效 . 让我知道 .

  • 1

    我不建议在计算字段中使用 store=True ,因为它们在某些情况下不能正常工作 . 所以,我认为你可以这样做:

    class Version(models.Model):
        _name = 'product_cars_application.version'
    
        name = fields.Char(
            compute="_compute_name",
            search="_search_name",
        )
    
        @api.one
        def _compute_name(self):
            self.name = "%s %s %s (%s)" % (self.brand_id,
                                        self.model_id.name,
                                        self.vname,
                                        self.year_id)
    
        def _search_name(self, operator, value):
            """ Actually this converts a domain into another one.
                With this new domain Odoo can search well
                A list of ids is the most easy way without computed fields
                    * [('id', 'in', id_list)]
            """
            if operator == 'ilike':
                name = self.env.context.get('name', False)
                if name is not False:
                    id_list = []
                    product_cars = self.env['product_cars_application.version'].search([])
                    for car in product_cars:
                        if name in car.name:
                            id_list.append(lot.id)
                    return [('id', 'in', lot_id_list)]
                else:
                    return [('id', 'in', [])]
            else:
                _logger.error(
                    'The field name is not searchable'
                    ' with the operator: {}',format(operator)
                )
    

    这是低效的,因为你总是要遍历所有记录,但我认为这是唯一安全的模式 .

    顺便说一句,对于您的特定情况,您可以做的最好的事情是将字段名称创建为普通字符,而不是计算 . 您可以设置默认值以创建名称 . 像这样, Value 将被存储,问题就会消失 .

相关问题