赖伟忠
赖伟忠

Reputation: 23

how to search other field in many2one?

python code:

_name = 'res.partner.table2'

customer_id = fields.Many2one('res.partner', required=True ,string="Customer ID")

XML:

<field name="arch" type="xml">
      <form string="Reward Points">
            <field name="customer_id"/>  //how can i search by res.partner customer_id in here 
      </form>
</field>

I need search by other field instead "name". How is it possible?

Upvotes: 2

Views: 1261

Answers (3)

Bishal Ghimire
Bishal Ghimire

Reputation: 687

I had same issue, I had to search through parent task in the task with id as well as name, this is how I did, I used name_search function to pass domain and use name_get to return the result. Hope it will be useful, good luck

@api.model
def name_search(self, name, args=None, operator='ilike', limit=100):
    args = args or []
    recs = self.browse()
    if not recs:
        recs = self.search(['|',('name', operator, name),('id', operator, name)] + args, limit=limit)
    return recs.name_get()

Upvotes: 0

Obay Abd-Algader
Obay Abd-Algader

Reputation: 1267

If for example you want to search by a new field (emp_code) in the hr.employee, I would suggest something like:

    @api.model
    def _name_search(self, name, args=None, operator='ilike', limit=100, name_get_uid=None):
        args = args or []
        domain = []
        if name:
            domain = ['|', ('emp_code', 'ilike', name), ('name', operator, name)]
            if operator in expression.NEGATIVE_TERM_OPERATORS:
                domain = ['&', '!'] + domain[1:]
        return self._search(expression.AND([domain, args]), limit=limit, access_rights_uid=name_get_uid)

The expression.NEGATIVE_TERM_OPERATORS will check for negative operators like !=.

This code was "inspired" by the one found at Odoo's account/models/account_account.py here.

Side note: all of Odoo's community version is inheriting from _name_search and not name_search

Upvotes: 0

Nish
Nish

Reputation: 36

We can achieve with following:

<field name="customer_id" context="{'my_custom_search': True}"/>

We add context to make sure functionality will effect to particular field and not disturb existing functionality.

class res_partner(models.Model):
    _inherit = 'res.partner'

    def name_search(self, cr, uid, name, args=None, operator='ilike', context=None, limit=100):
        if not args:
            args = []
        if not context:
            context = {}
        if context.has_key('my_custom_search'):
            domain = [('field_name', 'operator', value)]
            ids = self.search(domain)
        else:
            return super(res_partner, self).name_search(cr, user, name, args=args, operator='ilike', context=context, limit=limit)
        return self.name_get(cr, uid, ids, context)

Upvotes: 1

Related Questions