Development Book V18: Extending create() and write()

In real-world applications, you may need to introduce custom logic when a record is created or updated. Odoo allows you to override the create() and write() methods in a model to implement such custom behavior.

The create() method is called when a new record is being created. You can override it to insert custom logic before the record is saved in the database.

Example Use Case:

Let’s say you want to restrict users who are not part of the “Administration/Access Rights” group from editing a notes field in the sale.order model.

from odoo import models, fields, _
from odoo.exceptions import UserError

class SaleOrder(models.Model):
    _inherit = 'sale.order'

    notes = fields.Text(string='Notes')

    def create(self, vals):
        if 'notes' in vals and not self.env.user.has_group('base.group_erp_manager'):
            raise UserError(_("You cannot set the field 'notes'"))
        return super().create(vals)
  • vals contains the data passed for creation.
  • If 'notes' is present and the user is not in the allowed group, a UserError is raised.
  • super().create(vals) ensures the normal creation flow continues if validation passes.

The write() method is used when updating existing records. Overriding it allows you to control or restrict what can be modified.

Use Case:

Restrict the editing of the notes field to users who are part of the "Administration / Access Rights" group.

from odoo import models, _
from odoo.exceptions import UserError

class SaleOrder(models.Model):
    _inherit = 'sale.order'

    def write(self, vals):
        # Check if 'notes' is being updated by a non-admin user
        if 'notes' in vals and not self.env.user.has_group('base.group_erp_manager'):
            raise UserError(_("You cannot edit the field 'notes'"))
        # Call the original write method
        return super(SaleOrder, self).write(vals)
  • The logic mirrors that of the create() method.
  • By inspecting vals, you can determine whether a restricted field is being modified and apply conditional logic accordingly.
whatsapp_icon
location

Calicut

Cybrosys Technologies Pvt. Ltd.
Neospace, Kinfra Techno Park
Kakkancherry, Calicut
Kerala, India - 673635

location

Kochi

Cybrosys Technologies Pvt. Ltd.
1st Floor, Thapasya Building,
Infopark, Kakkanad,
Kochi, India - 682030.

location

Bangalore

Cybrosys Techno Solutions
The Estate, 8th Floor,
Dickenson Road,
Bangalore, India - 560042

Send Us A Message