Set default value Many2one in Odoo 8

Set default value on Many2one :V7 and V8 with a single line solution

In this tutorial I will explain you how to set a default value in a Many2one relation with 3 solution.
Version 7
The first step is to create a new Many2one field.
‘currency_id’: fields.many2one(‘res.currency’, string=“Currency”),
-add default values
defaults = {
‘currency_id’: _get_default_currency,
    }
As you can see this links to _get_default_currency which is another function.
Create a function which sets the value :
def _get_default_currency(self, cr, uid, context=None):
“”” Search for Currency TND by default
“””
res = self.pool.get(‘res.company’).search(cr, uid, [(‘currency_id’,’=’,’TND’)], context=context)
return res and res[0] or False
Then add the field to your view (.xml file):
<field name=“currency_id”/>
Version 8
The First Step is to create a function which sets the value :
@api.model
def _def_currency(self):
“”” Search for Currency TND by default
“””
currency_obj= self.env[‘res.company’]
currency = currency_obj.search([(‘currency_id’,’=’,’TND’)], limit=1)
if currency:
return currency[0].id
return False
Then create a new Many2one field and set links to the function _def_currency
currency_id = fields.Many2one(res.company’, ‘Currency’,default=_def_currency)
Then add the field to your view (.xml file):
<field name=“currency_id”/>
Single Line : Best Solution
Also you can create new field in new api, a single line solution.
currency_id = fields.Many2one(‘res.currency’, ‘Currency’, default=lambda self: self.env.user.company_id.currency_id.search([(‘name’,’=’,’TND’)]))