In this article I will show you how to create a many2many field in Odoo. I will also show you guys how to filter many2many field using domain. You can also learn how to set default value on many2many field.
How to create many2many field in Odoo
Read More: How to Create Model and Fields in Odoo
your_many2many_field = fields.Many2many('model.name','your_many2many_table_name', 'column_1','columns_2', string="My many2many Field")
Code Description
- "model.name" is the name of that model which you want to select/show as many2many.
- "your_many2many_table_name" is the name of third table, you can write any name as you want.
- "column_1" will be parent table reference or id.
- "columns_2" will be many2many table reference or id.
Add domain on many2many field in Odoo.
Now we will add domain on many2many field.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@api.multi | |
def _add_domain(self): | |
user_obj = self.env['res.users'].search([('department_id','=',self.env.user.department_id.id)]) | |
if user_obj: | |
domain = [('id', 'in', user_obj.ids)] | |
else: | |
domain = [('id', '=', -1)] | |
return domain | |
your_many2many_field = fields.Many2many('model.name','your_many2many_table_name', 'column_1','columns_2', string="My many2many Field",domain=_add_domain) | |
Code Description
In above code we have added "domain=_add_domain" and create a function that will return our desired ids which we want to load/filter on many2many field.
Read More: Apply domain on many2one field in Odoo
Load default value on many2many field.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@api.multi | |
def _load_default_user(self): | |
user_obj = self.env['res.users'].search([('department_id','=',self.env.user.department_id.id)]) | |
if user_obj: | |
return user_obj.ids | |
else: | |
return [] | |
your_many2many_field = fields.Many2many('model.name','your_many2many_table_name', 'column_1','columns_2', string="My many2many Field",default=_load_default_user) | |
How can i select only the users belongs to a particular group in a many2many field
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
user_ids = fields.Many2many('res.users', string='Recipients', | |
domain=lambda self: [("groups_id", "=", | |
self.env.ref("base.group_erp_manager").id)]) |
2 Comments
So simple, so nice!
ReplyDeleteCool bro!
thanks :)
Delete