How to Override the Write Method in Odoo

Abid Patel
11-Oct-2024 Updated : 11-Oct-2024

Learn how to override the write method in Odoo to add custom logic, validation, and actions when updating records. Step-by-step guide with examples.

How to Override the Write Method in Odoo

The write method in Odoo is used to update existing records in the database. Overriding this method allows developers to implement custom logic and validation when modifying records. In this blog post, we will explore how to override the write method in Odoo with practical examples to enhance functionality and maintain data integrity.

What is the Write Method in Odoo?

The write method is part of Odoo's ORM (Object-Relational Mapping) framework, allowing users to modify existing records in a model. It takes a dictionary of field names and their corresponding values as input, updating the specified fields for the record(s). By overriding this method, you can add custom behavior before or after the record is updated.

Why Override the Write Method?

Overriding the write method can be useful for various reasons, such as:

  • ▹ Implementing custom validation logic.
  • ▹ Logging changes made to specific fields.
  • ▹ Triggering additional actions based on field updates.
  • ▹ Enforcing business rules or constraints.

How to Override the Write Method in Odoo

To override the write method in Odoo, follow these steps:

Step 1: Inherit the Model

To start, you need to inherit the model you want to modify. For example, let’s say we want to override the write method for the res.partner model, which manages contacts in Odoo.

Python

from odoo import models, api

class CustomPartner(models.Model):
    _inherit = 'res.partner'

Step 2: Override the Write Method

Next, you can override the write method. Here’s an example of how to do this:

Python

    @api.multi
    def write(self, vals):
        # Custom logic: Log changes to the 'name' field
        if 'name' in vals:
            # Log the change or perform some validation
            old_name = self.name
            new_name = vals['name']
            _logger.info(f'Changing name from {old_name} to {new_name}')

        # Call the original write method to ensure standard behavior
        result = super(CustomPartner, self).write(vals)
        
        return result

In this example:

  • ▹ We check if the name field is being updated in the vals dictionary.
  • ▹ We log the old and new values of the name field for auditing purposes.
  • ▹ Finally, we call the original write method using super() to ensure that the record is updated correctly.

Adding Custom Validation

Overriding the write method is also a great opportunity to implement custom validation logic. For example, let’s ensure that the email address of a partner is in the correct format:

Python

import re
from odoo.exceptions import ValidationError

class CustomPartner(models.Model):
    _inherit = 'res.partner'

    @api.multi
    def write(self, vals):
        if 'email' in vals:
            email = vals['email']
            if not re.match(r'^[^@]+@[^@]+\.[^@]+$', email):
                raise ValidationError("Invalid email address format.")

        # Call the original write method
        return super(CustomPartner, self).write(vals)

In this example:

  • ▹ We check if the email field is being updated.
  • ▹ We use a regular expression to validate the email format. If it’s invalid, we raise a ValidationError.
  • ▹ We then call the original write method to apply any valid changes.

Triggering Actions Based on Field Updates

You can also trigger actions based on the fields being updated. For instance, if a partner's status is updated, you might want to send a notification:

Python

class CustomPartner(models.Model):
    _inherit = 'res.partner'

    @api.multi
    def write(self, vals):
        # Check if the status field is updated
        if 'status' in vals:
            # Trigger a notification or action
            self.env.user.notify_success('Partner status updated.')

        # Call the original write method
        return super(CustomPartner, self).write(vals)

In this case, if the status field is updated, a notification is sent to the user after the record is written.

Best Practices for Overriding the Write Method

When overriding the write method, consider the following best practices:

  • Always call super(): Ensure that the base method is called to maintain the original functionality.
  • Keep logic concise: Avoid overly complex logic within the write method to enhance maintainability.
  • Handle exceptions: Properly handle any exceptions or validation errors to ensure data integrity.

Conclusion

Overriding the write method in Odoo allows you to implement custom logic, validate data, and trigger additional actions whenever records are updated. By following the steps outlined in this blog, you can easily enhance your Odoo applications to meet specific business requirements. Whether you need to log changes, validate input, or automate actions, the write method provides a flexible way to customize record updates in Odoo.

For more Odoo development tips and tricks, be sure to check our website Free web snippets.

Make a Comment

Your email address will not be published. Required fields are marked *