2016-11-26 109 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) 
      ) 

這是低效的,因爲你總是要遍歷所有的記錄,但我認爲這是唯一安全的方式做到這一點。

順便說一句,您的特定情況下,你能做的最好的事情就是創建字段名稱作爲一個正常的字符,這沒有計算。您可以設置一個默認值來創建名稱。像這樣,價值將被存儲,問題會消失。

相關問題