Search code examples
odoo

How to set domain to Many2One fields in odoo?


I have an entity teacher with a Many2One field "substitute_teacher_id". The idea is that a teacher can replace other teacher, but a teacher should not be able to replace himself. How can I set that restriction in the teacher's model and/or view to ensure that a teacher cannot select a teacher with the same id as a substitute? This is my code

class Teacher(models.Model):
    _name = 'school.teacher'
    _description = 'School Teacher'

    name = fields.Char(string="Name")
    substitute_teacher_id = fields.Many2one('school.teacher', string="Sustitute")

Solution

  • You need to expose id field before substitute_teacher_id field in from view.

    Now add following domain in it:

    <field name="substitute_teacher_id" domain="[('id', '!=', id)]"/>
    

    EDIT:

    <field name="id" invisible="1"/>
    <field name="substitute_teacher_id" domain="[('id', '!=', id)]"/>