In this article you will learn how to return domain on onchange of many2one field in Odoo. In other words we are going to create a dependent drop down (many2one) field in Odoo. 

Set or Return Domain of Many2One Field OnChange of Another Field


Return Domain on Onchange of Many2One Field

For example I have two many2one fields (campus_id and department_id), and we want to change the department on the basis of campus field. To achieve this we will use @api.onchange function provided by Odoo and return domain filter.


campus_id = fields.Many2one('model.campus', string="Campus Name")
department_id = fields.Many2one('model.department', string="Department Name")

Code Description

In line no 1 we use @api.onchange decorator for campus_id. It means whenever campus changes or select a campus from many2one filed do the following line of code (3,4,5).  In line no 3 we declare a dict named res. In line no 4 we use domain to change the department field.

res['domain']      =     {'department_id':[('campus_id', '=', self.campus_id.id)]}
                                       |                                |
                                       |                                |
   (field name which is to changed)       (field name which is intended to change)