You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

76 lines
2.9 KiB

  1. # -*- coding: utf-8 -*-
  2. # © 2016 Daniel Reis
  3. # License AGPL-3.0 or later (http://www.gnu.org/licenses/agpl).
  4. from openerp import models, fields, api
  5. from openerp import SUPERUSER_ID
  6. from openerp import tools
  7. # Extended name search is only used on some operators
  8. ALLOWED_OPS = set(['ilike', 'like'])
  9. @tools.ormcache(skiparg=0)
  10. def _get_rec_names(self):
  11. model = self.env['ir.model'].search(
  12. [('model', '=', str(self._model))])
  13. rec_name = [self._rec_name] or []
  14. other_names = model.name_search_ids.mapped('name')
  15. return rec_name + other_names
  16. def _extend_name_results(self, domain, results, limit):
  17. result_count = len(results)
  18. if result_count < limit:
  19. domain += [('id', 'not in', [x[0] for x in results])]
  20. recs = self.search(domain, limit=limit - result_count)
  21. results.extend(recs.name_get())
  22. return results
  23. class ModelExtended(models.Model):
  24. _inherit = 'ir.model'
  25. name_search_ids = fields.Many2many(
  26. 'ir.model.fields',
  27. string='Name Search Fields')
  28. def _register_hook(self, cr, ids=None):
  29. def make_name_search():
  30. @api.model
  31. def name_search(self, name='', args=None,
  32. operator='ilike', limit=100):
  33. # Perform standard name search
  34. res = name_search.origin(
  35. self, name=name, args=args, operator=operator, limit=limit)
  36. enabled = self.env.context.get('name_search_extended', True)
  37. # Perform extended name search
  38. if enabled and operator in ALLOWED_OPS:
  39. # Support a list of fields to search on
  40. all_names = _get_rec_names(self)
  41. # Try regular search on each additional search field
  42. for rec_name in all_names[1:]:
  43. domain = [(rec_name, operator, name)]
  44. res = _extend_name_results(self, domain, res, limit)
  45. # Try ordered word search on each of the search fields
  46. for rec_name in all_names:
  47. domain = [(rec_name, operator, name.replace(' ', '%'))]
  48. res = _extend_name_results(self, domain, res, limit)
  49. # Try unordered word search on each of the search fields
  50. for rec_name in all_names:
  51. domain = [(rec_name, operator, x)
  52. for x in name.split() if x]
  53. res = _extend_name_results(self, domain, res, limit)
  54. return res
  55. return name_search
  56. if ids is None:
  57. ids = self.search(cr, SUPERUSER_ID, [])
  58. for model in self.browse(cr, SUPERUSER_ID, ids):
  59. Model = self.pool.get(model.model)
  60. if Model:
  61. Model._patch_method('name_search', make_name_search())
  62. return super(ModelExtended, self)._register_hook(cr)