Wednesday, 5 October 2016

Onchange many2one filed in odoo

Today you will learn how to create a dependent drop down (many2one) fields in Odoo. 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.

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

1     @api.onchange('campus_id')
2    def _campus_onchange(self):
3        res = {}
4        res['domain']={'department_id':[('campus_id', '=',]}
5        return res

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', '=',]}
                                       |                                |
                                       |                                |
   (field name which is to changed)       (field name which is intended to change)


  1. Please describe more in depth for better understanding.

  2. Is it possible to create a record of another model (a mail.activity) associated to the record that has changed?

    This is my code:

    def _onchange_stage_id(self):
    values = self._onchange_stage_id_values(
    event_user_id = self.user_id
    if == 3:
    self = self.env['event_mgmt.event_mgmt'].browse(
    activity = self.env['mail.activity']
    activity_ins = activity.create(
    'res_model_id': 170,
    'summary': 'Follow Up',
    'note':'Han pasado 5 días desde el paso a propuesta. Realizar seguimiento a la propuesta enviada.',
    'date_deadline': + timedelta(days=5),
    'previous_activity_type_id': False,
    'recommended_activity_type_id': False,

    The onchange applies to a crm.lead record and I would like to create an activity (as a reminder) when the stage changes.

    Any help would be very appreciated

    1. under your onchange methode use below code snippet to create records for another model:

      values = {

      create_another_model_records = self.env['another.model'].create(values)