Search code examples
searchodooodoo-9odoo-viewcomputed-field

How can I search by a computed field in Odoo?


I'm trying to search by a computed field in Odoo 9. But it return all record as result.

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)

I have tried with store=True and without it, but the name field is not stored in the databse. I have also tried to delete the column "name" from the database, then I have updated the module but it isn't storing the computation. The computed field works fine on the form view, but the name is not stored, and the search is not working.

So, how can I search by the field name?


Solution

  • Add this to your code.

     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)
    

    You can see details in the docs.

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

    Section "Computed Fields" is for you.

    Hopefully it will work. Let me know.