tuấn anh phạm
tuấn anh phạm

Reputation: 81

How can I set default value for a many2one field in odoo 9?

I am new with Odoo-9.0c system and try to make some change to support the work. But I don't know how to set a specific value for many2one field ((selection type). The field also has been created through a custom module. what is the right way to solve this kind of problem?

Upvotes: 1

Views: 6956

Answers (3)

Ridma Gimhani
Ridma Gimhani

Reputation: 133

You can use lambda to set default:

type = fields.Many2one('your.model',"String to display", default=lambda self: self.env['your.model'].search([('name','=','value you need to set as default')]))

Upvotes: 0

Kenly
Kenly

Reputation: 26678

With the new api, just specify which field attribute to change:

field_name = fields.Many2one(default=a_function)

From Odoo new api guide line

Field inheritance

One of the new features of the API is to be able to change only one attribute of the field:

name = fields.Char(string='New Value')

...

Fields Defaults

Default is now a keyword of a field:

You can attribute it a value or a function

name = fields.Char(default='A name')

or

name = fields.Char(default=a_fun)

...

def a_fun(self):  
    return self.do_something()

Upvotes: 1

Phillip Stack
Phillip Stack

Reputation: 3378

If you wish to use something dynamic you can define a function which will set the default for the field in your record. In your function you will need to identify the id of the record on your related model and assign the value of your field to that id.

@api.multi
def _get_field_name_default(self):
    related_model_id = self.env['related.model'].search([<YOUR DOMAIN HERE>]).id
    return related_model_id

field_name_id = fields.Many2one('model.name', string="Field Title", default=_get_field_name_default)

If this value is expected to alway be the same and you already know that id of the record in your related model then you could assign it statically.

field_name_id = fields.Many2one('model.name', string="Field Title", default=1)

Better to use a function which is capable of returning False or None in the event the record on your related model has been removed.

Upvotes: 1

Related Questions