In Odoo, the create, write, and unlink methods play a crucial role in handling database operations. These methods are responsible for creating new records, updating existing ones, and deleting records, respectively. However, in many cases, businesses require additional custom logic when performing these operations.
Odoo provides a way to override these methods, allowing developers to add custom behavior while maintaining Odoo's core functionalities. Whether you want to apply business rules, log changes, or trigger automated actions, understanding how to override these methods is essential for customizing Odoo to meet specific needs.
In this blog, we will explore how to properly override create, write, and unlink methods in Odoo 18, along with best practices to ensure smooth and efficient implementation.
The create, write, and unlink methods are essential for managing records in Odoo’s database:
* Create Method: Called when a new record is added to a model.
* Write Method: Executes when an existing record is updated or modified.
* Unlink Method: Runs when a record is deleted or removed from its associated model.
Overriding the Create Method in Odoo 18
The create() method is triggered when a new record is added to a model. By overriding this method, we can introduce custom validations or modify the record before it gets stored in the database.
For example, let's enforce a rule that requires the mobile field to be mandatory when creating a new partner record in the res.partner model:
from odoo import models, api, exceptions
class ResPartner(models.Model):
_inherit = "res.partner"
@api.model_create_multi
def create(self, values):
# Ensure the 'mobile' field is provided
if 'mobile' not in values or not values.get('mobile'):
raise exceptions.ValidationError(
"Mobile is a mandatory field. Please provide a mobile number.")
# Call the original create method
return super(ResPartner, self).create(values)
Code Breakdown
* class ResPartner(models.Model): _inherit = "res.partner"
- This class extends the standard res.partner model.
- The _inherit attribute allows us to modify the existing model without altering its core structure.
* @api.model_create_multi
- This decorator optimizes the method for handling multiple records at once.
- It ensures that the method is compatible with Odoo’s batch processing.
* Mobile Field Validation
if 'mobile' not in values or not values.get('mobile'):
raise exceptions.ValidationError("Mobile is a mandatory field. Please provide a mobile number.")
- This checks if the mobile field is present and not empty.
- If the field is missing, an exception is raised, preventing record creation.
* Calling the Parent Method
return super(ResPartner, self).create(values)
- Calls the default create() method of res.partner to ensure standard behavior is maintained.
- This allows Odoo’s built-in logic to execute while enforcing our custom validation.
By overriding the create() method this way, we ensure that every partner record has a mobile number, preventing incomplete or invalid data from being saved.
Overriding the Write Method in Odoo 18
The write() method is triggered when an existing record is updated. While we enforced the mobile field as mandatory in the create() method, users can still update a record without adding a mobile number. To prevent this, we override the write() method to ensure the mobile field remains mandatory during updates as well.
from odoo import models, api, exceptions
class ResPartner(models.Model):
_inherit = "res.partner"
def write(self, values):
# Ensure the 'mobile' field is provided and not empty when updating
if 'mobile' in values and not values['mobile']:
raise exceptions.ValidationError(
"Mobile is a mandatory field. Please provide a mobile number.")
# Call the original write method to update the record
return super(ResPartner, self).write(values)
Code Breakdown
* def write(self, values):
- This method is called when an existing record in res.partner is modified.
* Mobile Field Validation
if 'mobile' in values and not values['mobile']:
raise exceptions.ValidationError("Mobile is a mandatory field. Please provide a mobile number.")
- Checks if the mobile field is included in the update request.
- If it exists but is empty, it raises a validation error to prevent saving incomplete data.
* Calling the Parent Method
return super(ResPartner, self).write(values)
- Calls Odoo’s default write() method to handle record updates.
- Ensures all other standard behaviors and rules of res.partner are maintained.
By overriding the write() method, we enforce that the mobile field remains mandatory, even during updates, ensuring data consistency across the system.
Overriding the Unlink Method in Odoo 18
The unlink() method is triggered when a record is deleted. To prevent unauthorized deletions, we can override this method to ensure that only users with admin privileges can delete records.
from odoo import models, exceptions
class ResPartner(models.Model):
_inherit = "res.partner"
def unlink(self):
# Check if the user has admin privileges
if not self.env.user.has_group('base.group_erp_manager'):
raise exceptions.UserError(
"Only an administrator can delete partner records.")
# Call the original unlink method to delete the record
return super(ResPartner, self).unlink()
Code Breakdown
* def unlink(self):
- This method is executed when a record from the res.partner model is being deleted.
* Checking Admin Privileges
if not self.env.user.has_group('base.group_erp_manager'):
raise exceptions.UserError("Only an administrator can delete partner records.")
- Verifies if the current user belongs to the ERP Manager group (base.group_erp_manager).
- If the user lacks admin rights, an exception is raised, preventing deletion.
* Calling the Parent Method
return super(ResPartner, self).unlink()
- Calls Odoo’s default unlink() method to proceed with record deletion.
- Ensures that all standard Odoo rules and behaviors are preserved.
By overriding the unlink() method, we enforce strict access control, preventing unauthorized users from deleting important partner records.
Overriding the create(), write(), and unlink() methods in Odoo 18 allows developers to enforce business rules, maintain data integrity, and implement access restrictions. By customizing these methods, we can ensure that records are created with mandatory fields, updated with proper validations, and deleted only by authorized users. Properly implementing these overrides enhances system reliability and security while aligning Odoo’s functionality with business requirements.
To read more about How to Override Create, Write, & Unlink Methods in Odoo 17, refer to our blog How to Override Create, Write, & Unlink Methods in Odoo 17.