Search code examples
pythonodooodoo-10many-to-one

Odoo, how to hide an item from many2one field?


Odoo-10

My .py

class komMo(models.Model):
    _name = 'kom.mo'

    mo_id = fields.Integer(string='Code mo') #this is just the recognition number
    name = fields.Char(string='Name mo') 

    parent_id = fields.Many2one('kom.mo')

Form for editing

I want to hide the option(example) from the drop list ('parent_id'), if that is the name of the object itself

So when I'm going to edit an 'example', I do not want to be offered as an option in the field 'parent_id'

When I create a new 'example2' it's all good, because only the existing items are displayed in the drop-down list.

If I was not clear please tell me. my .xml file was pretty basic i did not add any options or attributes


Solution

  • Just add this domain to the field domain="[('id', '!=', id)]". That will remove the object for its own form.

    You can also use odoo's nested set system for parent child relationship, which has great benefit in resolving parent child relationship query, by setting _parent_store = True in models definition, and adding parent_left, parent_right fields, you can the also use @api.constraint on parent_id calling odoo Models _check_recursion to ensure that there is no recursive parent child relationship creation. For example on odoo Product category model:

    class ProductCategory(models.Model):
        _name = "product.category"
        _description = "Product Category"
        _parent_name = "parent_id"
        _parent_store = True
        _parent_order = 'name'
        _rec_name = 'complete_name'
        _order = 'parent_left'
    
        parent_id = fields.Many2one('product.category', 'Parent Category', index=True, ondelete='cascade')
        parent_left = fields.Integer('Left Parent', index=1)
        parent_right = fields.Integer('Right Parent', index=1)
    
        @api.constrains('parent_id')
        def _check_category_recursion(self):
            if not self._check_recursion():
                raise ValidationError(_('Error ! You cannot create recursive categories.'))
            return True