• Tek Siong, Hock

Odoo Technical - Set the default values for your field

Updated: Mar 3

This Odoo technical development blog is my way to contribute back to the Odoo Community, for all the selfless and great sharing by the community members.



1) Default parameter in the field

Get the default value when the field is initiated, by calling a method.

@api.model
def _set_department(self):
    employee_rec = self.env['hr.employee'].search([('user_id', '=', self.env.user.id)])
    department = employee_rec.department_id
    return department

department = fields.Many2one('hr.department', string="Department", default=_set_department)

2) default_get method

Loading the default values to the fields, when the view is loading or in the wizard.

@api.model
def default_get(self, fields):
    res = super(Lead2OpportunityMassConvert, self).default_get(fields)
    if 'partner_id' in fields:  # avoid forcing the partner of the first lead as default
        res['partner_id'] = False
    if 'action' in fields:
        res['action'] = 'each_exist_or_create'
    if 'name' in fields:
        res['name'] = 'convert'
    if 'opportunity_ids' in fields:
        res['opportunity_ids'] = False
    return res

3) create method


@api.model
def create(self, vals):
    vals['field_name'] = XXXXX
    
    return super(ClassName, self).create(vals)

4) Use the context to pass the default values to the wizard, just by setting value to the default_fieldname.


context = {
    'active_ids' : self.ids,
    'active_model' : self._name,
    'active_id' : self.id,
    'default_amount' : self.amount_residual,
    'default_currency_id' : self.currency_id.id,
    'default_communication' : self.ref,
    'default_account_netting_id' : self.id            
    }        

5) Update the default value of the existing field in the model

Eg, if you want to create the customer as Company by default, instead of standard "Individual", you may inherit the res.partner and simply overwrite the default.


is_company = fields.Boolean(string='Is a Company', default=True, help="Check if the contact is a company, otherwise it is a person")




Click "Like" at the bottom of this blog, to motivate us to continue sharing more Odoo tips.


948 views0 comments