Set default value Many2one in Odoo 8

Hi guys,

In this tutorial I will explain you how to set a default value in a Many2one relation. I will add a new field to the quotations view which is a Many2one to all the currencies to demonstrate this.
Tip: You can view my sample module here.

1. Creating the field

The first step is to create a new Many2one field that is linked to another model. Simply add a field to your .py file that creates the model. For example:

2. Adding the field to view

Then add the field to your view (.xml file):

If you now go to the view where you’ve added this field you will see a dropdown (Many2one) but there is no default value set.
Default Many2one behaviour

3. Set default value on Many2one

The next step is to go back to your .py file and add default values. Do this by adding your field between defaults {}.

As you can see this links to _get_default_currency which is another function in the same .py file. Create a function above this code which sets the value.

So what does this do? When the user wants to create a new quotation and the record opens the defaults {} will be called. This links to the field currency_id_invoices which links to the function that sets the currency in the Many2one. In this function we will go to the table and search for the record where the currency_id is equal to EUR, the currency I want to set by default. When it is found it will be set in the Many2one, otherwise nothing will be set.
The result:
Default value

As you can see the currency is now filled in when you create a new record and the user can still change it whenever he wants to. Want to see this module in action? You can download / view it on my Github.
You can find more information about Many2one relations here.
Tutorial sponsored by Oocademy