Automatically fill Many2many in Odoo
5 March, 2021 by
Automatically fill Many2many in Odoo
Administrator
| No comments yet


In this tutorial I will learn you how to automatically fill a Many2many with data. In some cases a many2many always has to have data so in that case having it filled in automatically is really handy.

1. Creating the model

The first step is to create a new model with fields from which we want to get data. (in case you already have a model where you want to load from skip to chapter 2)
In my example I want to create a many2many which gets all records from the model sale.order.printorder and automatically adds them, so lets first create the model sale.order.printorder:

2. Create and fill many2many

After the model is made we now have to fill up the many2many. Create a many2many to your other model and add the default parameter to it:

As you can see there is a default=_get_default_print_order_ids which links to a function in the class. This function will automatically get all data from the model sale.order.printorder thanks to self.pool. After the pool got all records we will return all the data and it will be added to the many2many.
Now lets create a view that shows the many2many:

When a user would now create a new quotation/order there will be a new tab named ‘Many2many demo’ which is automatically filled with all records from the model sale.order.printorder:
Automatically added records to many2many

3. Creating default records for sale.order.printorder

Want to go further and want to have the records generated by default when the module is installed? Then create a new XML file where you create new records. I’ve created a file defaultdata.xml in my module and added the following records:

TIP: Add the filename defaultdata.xml to __openerp__py under ‘data’.
When the module is installed these records will be automatically created in the database and will never be updated thanks to the noupdate=”1″. When you need a many2many filled with default data that always has to be the same this is perfect. If this is not the case simply create a new view where users can create new records in to the model sale.order.printorder!

Do you want to see the source code or try this module out? You can download / view it on Github!
Has this tutorial helped you, do you have any feedback or questions? Post away!

Sign in to leave a comment