Search code examples
odooinventory

Odoo 10 or above - enhance search


after removing filter_domain , it shows error:

enter image description here


** Updated 1st Feb 2018 **

Here is a code under a path in my ..odoo/addons/ted/models/ted_inventory.py

from odoo import api, fields, models

class TedInventory(models.Model):
    _inherit = 'stock.picking'

    trackingnum = fields.Char('trackingnum', readonly=True, index=True, help="Tracking number")  
    custom_name = fields.Char(string='Tracking Number',compute='_compute_custom_name',search='_search_custom_name')

    @api.multi
    @api.depends()
    def _compute_custom_name(self):
       ''' The field has to be a computed field
        You do not need to do anything here
       '''
       pass

    def _search_custom_name(self, operator, value):
        res = []
        if operator == 'ilike':
            query = "SELECT id FROM stock_picking WHERE position(trackingnum in %s) >= 1"
            self._cr.execute(query, (value,))
            res_ids = [x[0] for x in self._cr.fetchall()]
            res.append(('id', 'in', res_ids))
            return res

I am sure my app is installed as I can find the custom_name and trackingnum in stock.picking model.

I have also included a new search code in SearchView as: enter image description here

When I search like this here, the search result is nothing (as I expect to dig out record of TN1234):

enter image description here


Solution

  • The operator that you are using for is wrong couse ilike search the value into field but you need the other wise, search the field into the value, I got a solution for your problem but I don't think that it is the best approach, but it works:

    In SQL: position(field in str), search field into str.

    def _search_custom_name(self, operator, value):
        res = []
        if operator == 'ilike':
            query = "SELECT id FROM stock_picking WHERE position(trackingnum in %s) >= 1"
            self._cr.execute(query, (value,))
            res_ids = [x[0] for x in self._cr.fetchall()]
            res.append(('id', 'in', res_ids))
            return res
    

    You need to consider the others operators too.

    I hope this could be helpful for you!