how-to-override-methods-or-models-in-odoo-18

How to Override Methods or Models in Odoo 18

Odoo, one of the most popular open-source ERP systems, provides immense flexibility and customization options to adapt the software to your unique companies needs. Whether you want to add custom fields, modify business logic, or change the system’s behaviour, Odoo allows you to extend and override its built-in models and methods without altering its core code.

The ability to override methods or models in Odoo is a critical feature that allows businesses to tailor Odoo’s functionality to specific processes. With the flexibility of Odoo’s powerful object-relational mapping (ORM) framework, developers can safely customize the system to ensure upgrade compatibility and maintain clean code practices.

In this blog, we’ll explore:

  1. How to Override a Model
  2. How to Override a Method (Standard and Computed)
  3. Best Practices for Customization (Odoo Customization services)

How to Override a Model

Override methods or models in Odoo represent the data structure for various business objects like customers, products, sales orders, etc. Overriding a model allows you to add new fields, modify existing fields, or extend the functionality of Odoo’s built-in models.

Steps to Override a Model:

Inherit the Model in Python:

To override methods or models in Odoo, the first step is to inherit the existing model in your custom module. You can do this by creating a new Python class that extends the desired model. For example, if you want to add a custom field to the res.partner model (which represents partners or customers), the Python code would look like this:

				
					from odoo import models, fields

class ResPartner(models.Model):
    _inherit = 'res.partner'  # Inheriting existing model

    x_custom_field = fields.Char(string="Custom Field")

				
			

In this example, we add a new x_custom_field of type Char (a text field) to the res.partner model. Using the inherit attribute, we extend the model and add the new field, appearing in all partner-related forms and views.

Update the View in XML:

After modifying the override methods or models in Odoo, you need to update the corresponding form view in XML like Odoo XML RPC to display the new field. Odoo’s views define how the model data is presented to the user in the interface. To update the form view for the res.partner model, use the following XML code:

				
					<?xml version="1.0" encoding="UTF-8"?>
<odoo>
    <record id="view_partner_form_inherit_custom" model="ir.ui.view">
        <field name="name">res.partner.inherit.form</field>
        <field name="model">res.partner</field>
        <field name="inherit_id" ref="base.view_partner_form"/>
        <field name="arch" type="xml">

                   <field name="name" position="after">
                <field name="x_custom_field"/>
            </field>

        </field>
    </record>
</odoo>

				
			

In this XML code:

  • We reference the original partner form view (base.view_partner_form).
  • Using the inherit_id attribute, we tell Odoo that we’re modifying this existing view.
  • The position=”after” attribute places the new x_custom_field right after the name field in the form.

This ensures that the new field will appear smoothly in the user interface without breaking the original layout.

How to Override a Method in Odoo

Override methods or models in Odoo define the behavior of models. You can override built-in methods to customize how records are created, updated, or deleted and modify business logic in computations or actions triggered by buttons.

Overriding the Create Method:

The create method is one of the most commonly overridden methods in Odoo. This method is called when a new record is created in the database. For instance, if you want to automatically capitalize the name field when creating a new partner, You can override:

  • Regular methods (e.g., create, write, unlink)
  • Compute methods
  • Button or action methods

Overriding the create method:

The create method is one of the most commonly overridden methods in Odoo. This method is called when a new record is created in the database. For instance, if you want to automatically capitalize the name field when creating a new partner, you can override the create method like this:

This is the code will write in python file

				
					from odoo import models, fields, api
class ResPartner(models.Model):
    _inherit = 'res.partner'
    @api.model_create_multi
    def create(self, vals_list):
        for vals in vals_list:
            if 'name' in vals and vals['name']:
                vals['name'] = vals['name'].upper()
        return super().create(vals_list)

				
			

Overriding a Compute Method:

Computed fields in Odoo are fields whose value is calculated dynamically based on other fields. You can override the compute method for a field to modify how the value is calculated.

For example, let’s say we have a sale.order model with a custom computed field called custom_total, which calculates the total value of all order lines. Here’s how you can override the compute method:

				
					from odoo import models, fields, api
class SaleOrder(models.Model):
    _inherit = 'sale.order'
    custom_total = fields.Float(string="Custom Total", compute="_compute_custom_total")
    @api.depends('order_line')
    def _compute_custom_total(self):
        for record in self:
            record.custom_total = sum(line.price_total for line in record.order_line)

				
			

Best Practices for Overriding Models and Method

When overriding methods or models in Odoo, it’s important to follow best practices to ensure the stability and maintainability of your Odoo instance. Here are some key practices to keep in mind:

1. Always Use super() When Overriding Core Methods

Using super() ensures that the original functionality of the method is preserved. If you override a method like create or write, always call the parent method to maintain the existing behavior unless you want to completely replace it.

For example:

				
					return super().create(vals_list)
				
			

This ensures that the create method works as expected, even after adding custom logic.

2. Use ORM Methods for Database Operations

Avoid using raw SQL queries to interact with the database. Instead, use Odoo’s ORM methods (create, write, unlink, etc.) to handle database operations. These methods ensure that the data is properly validated, and they trigger the necessary automated actions (such as updating related records).

For example, always use

				
					record.write({'field_name': value})

				
			

Instead of directly updating the database.

3. Add Module Dependencies

If your module depends on other modules (for example, if you inherit models from them), be sure to add those dependencies in the __manifest__.py file. This ensures that Odoo loads the required modules before yours.

Example of adding a dependency:

				
					{
    'name': 'Custom Module',
    'depends': ['base', 'sale'],
    'data': ['views.xml'],
}

				
			

This tells Odoo that your custom module depends on the base and sale modules.

4. Thorough Testing Is Crucial

Customization is powerful but should be done carefully. Overriding core methods such as create, write, or unlink can have significant effects on your data and application behavior. Always test your customizations thoroughly in a development environment before deploying them to production.

Create test cases for each method you override and validate that your custom logic works as expected.

For clear code we can follow these steps:

Always use super() when overriding core methods to maintain original functionality unless you fully replace it.

Avoid direct database changes. Use ORM methods (create, write, unlink).

Add module dependencies in __manifest__.py if you inherit models from them.

Test thoroughly, especially if overriding sensitive methods like create, write, or unlink.

Override Methods or Models in Odoo

Odoo’s flexibility allows you to easily adapt the system to your business needs by overriding models and methods. Whether adding custom fields, modifying existing behaviour, or introducing new business logic, understanding how to override models and methods correctly is essential for ensuring that your customizations are effective and maintainable.

By following the best practices discussed in this blog, such as using super(), relying on Odoo’s ORM methods, and thoroughly testing your changes, you can create robust and customized solutions for your business while ensuring compatibility with future Odoo updates.

Odoo’s ORM framework provides a clean, safe, and scalable way to implement customizations without altering the core code. As your business grows, your Odoo instance can grow with it, adapting seamlessly to changing needs.

Picture of Krishnaveni

Krishnaveni

I’m Krishnaveni, an Odoo Developer Intern passionate about Odoo ERP development, customization, and building efficient business solutions to enhance operations.

Get a free quote