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.

Odoo Experts

9 thoughts on “Set default value Many2one in Odoo 8

    • Yenthe666 says:

      Hi Daniel,

      That is correct, this is still in the old API. Sadly rewriting all code and tutorials asks a lot of time, which I at this point do not have. Nevertheless I don’t really think much people will complain for a fully free tutorial.

  1. This a more simple approach using the new API. The function is applied on the field definition itself. It determines the currency based on the company the user belongs to.

    currency_id = fields.Many2one(“res.currency”, “Currency”, required=True, default=lambda self: self.env[‘res.users’].browse(self._uid).company_id.currency_id)

  2. Ryan Chan says:

    It would be nice if you can create an example and explain how to leverage Many2One and One2Many to mimic the obsoleted One2One relation.

    I had been in a situation recently that to create a one one corresponding table with sales order line (say, the new table is sales order line details). Unfortunately, I wasn’t able to search out what’s the best practice to achieve this.

    So, I wish you can give us some insights. 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *