forvas
forvas

Reputation: 10189

How to change the default search field of a model in Odoo 10?

I'm trying to modify the default search engine of the existing model mail.message.

If you look for the word Hello, the search returns you all the messages whose record_name field contains Hello. But I need that it returns all the messages whose body contains Hello.

mail.thread model has a One2many field pointing to mail.message, and a lot of models inherit from mail.thread. For example, sale.order. Therefore, in the search view of sale.order you can do an advanced search and look for Messages. But as I wrote above, it's returning you the messages whose "title" (field record_name) contains the word you have wrote in the search textbox.

To change that, I did this:

@api.model
def _name_search(self, name='', args=None, operator='ilike', limit=100, name_get_uid=None):
    result = super(MailMessage, self)._name_search(
        name=name, args=args, operator=operator, limit=limit,
        name_get_uid=name_get_uid
    )
    mms = self.env['mail.message'].search([]).filtered(
        lambda r: name in r.body
    )
    l = [(r.id, r.record_name) for r in mms]
    return l

So far it's working OK, but I don't trust it's working OK in all cases, and I'm pretty sure that there must be a much better way to manage it.

Any ideas?

Upvotes: 1

Views: 1704

Answers (2)

forvas
forvas

Reputation: 10189

@Cherif comment is the right answer:

If you want this behaviour for one model just add a filter in search view. But if you want this behavior for all models you are doing the right thing here. Just update your code to take in consideration args argument because sometimes it contains other domains.

I wasn't taking into account the args, the operator and the limit parameters, so if I can't call the super of _name_search due to the situation, at least I must copy the part of the source code of _name_search which I'm not going to modify:

class MailMessage(models.Model):
    _inherit = 'mail.message'

    @api.model
    def _name_search(self, name='', args=None, operator='ilike', limit=100,
                     name_get_uid=None):
        if args is None:
            args = []
        domain = args + [
            '|', ('model', operator, name), ('body', operator, name),
        ]
        return super(MailMessage, self).search(domain, limit=limit).name_get()

Upvotes: 2

Quentin THEURET
Quentin THEURET

Reputation: 1232

Can you try :

@api.model
def _name_search(self, name='', args=None, operator='ilike', limit=100, name_get_uid=None):
result = super(MailMessage, self)._name_search(
    name=name, args=args, operator=operator, limit=limit,
    name_get_uid=name_get_uid
)
mms = self.env['mail.message'].search([('body', 'like', name)])
return [(r.id, r.record_name) for r in mms]

Upvotes: 2

Related Questions