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

时间:2016-11-26 14:19:12

标签: search odoo odoo-9 odoo-view computed-field

我试图通过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 :(得分:1)

将此添加到您的代码中。

 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

Section" Computed Fields"是给你的。

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

答案 1 :(得分:1)

我不建议您在计算字段中使用store=True,如果它们不是完全必要的话(如果您想要group by此字段,则需要这样做),因为它们在某些情况下效果不佳,尽管最新版本工作得更好。所以,我认为你可以这样做:

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)
            )

考虑到这种搜索方式比在数据库中存储值更低效,因为您总是需要遍历所有记录来计算值。

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