How to set dynamic domain filter for Many2one field in odoo?

admin 2019-9-5 7509


In this article I’m going to describe, how to set the dynamic domain to Many2one field base on onchange event with another Many2one field.


In odoo we can find main two option to make a domain,

1、Using XML syntax

2、Using python expression


But in here we use python expression,

Assume we have two fields call as “class” and “teacher”. We need to set domain for teacher to filter the related teachers list when change the class field. For that we can write an onchange function and make python list to set all teachers database id’s and return that data to domain expression.


First we need to declare the class and teacher field within the model class.

   school = fields.Many2one('institute.school', string='School')
   class = fields.Many2one('institute.class ', string='TERRITORY', domain="[(' school ', '=', school)]") #basic python domain use here 
   teacher = fields.Many2one('res.partner', string='Teacher')


Then we can write an onchange function to set dynamic domain for teacher field

   # set domain for teacher to filter the selected teachers according to the class value
   @api.onchange('class')
    def set_domain_for_teacher(self):
        class_obj =self.env['institute.teachers'].search([('class', '=', self.class.id)])
        teacher_list = []
        for data in class_obj:
            teacher_list.append(data.user.id)
        res = {}
        res['domain'] = {'teacher': [('id', 'in', teacher_list)]}
        return res


Code explanation 

line 54 - we use this expression to define onchange function in odoo and pass the values for onchange event.

line 55 - this is the function that run with the onchange event.

line 56 - from this expression we get the teacher id list as a return value.

line 57,58,59 - from this code segment,we can append the all related teacher ids to teachers_list[ ]

line 62 - we use this code segment to arrange the domain for teachers field. 

it's your turn to test this with your own environment. I hope you all enjoy this.   


最新回复 (0)
返回