2016-11-26 110 views
2

我试图通过计算字段在Odoo 9.搜索但它返回所有记录作为结果。如何使用Odoo中的计算字段进行搜索?

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没有它,但名称字段不存储在DATABSE。我也试图从数据库中删除列“名”,那么我已经更新了模块,但它没有存储的计算。计算的字段在窗体视图上工作正常,但名称不存储,并且搜索不起作用。

那么,怎样才能由我场名称进行搜索?

回答

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

节 “计算字段” 是给你的。

希望它会工作。让我知道。

+0

必须做一些改变 高清_name_search(个体经营,名称args =无,运营商= 'ILIKE',限制= 100): 如果运营商== '像': 运算符= 'ILIKE' 版本= self.search([( '姓名',操作员名)],极限=极限) 返回versions.name_get() –

+0

确定。我改变了我的代码以满足您的需求。有同样问题的人可以更好地理解我们在这里所做的。 – Nope

+0

我不建议在计算字段中使用'store = True',因为它们在某些情况下效果不好。 – ChesuCR

0

我不建议在计算领域使用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) 
      ) 

这是低效的,因为你总是要遍历所有的记录,但我认为这是唯一安全的方式做到这一点。

顺便说一句,您的特定情况下,你能做的最好的事情就是创建字段名称作为一个正常的字符,这没有计算。您可以设置一个默认值来创建名称。像这样,价值将被存储,问题会消失。

相关问题