
Learn how to inherit and use super functions in Odoo. This guide covers extending existing methods and adding custom logic with clear examples in Odoo 16.
In Odoo inheritance is crucial concept. It allows to modify or expand the functionality of existing models or methods. When someone inherits a class or function, they may fully override it. Alternatively they can keep the original function. This can be done using super() function.
In Odoo super function points to the method from the parent class. It can be an original function. This function can be invoked within an inherited class. We see this function's use when we override method. However we may also want to call the original method of parent class. This is needed to preserve the parent's class functionality.
With super() it is possible to call the parent class method. The use of this function enables child class to modify behavior. It can also allow a child to extend the behavior. But this happens without completely replacing the original method, thus maintaining parent class method use.
Imagine we desire to expand the functionality of create() method in sale.order model. This method's role is in creation of new sales orders in Odoo. However we want to insert custom logic. Say, for instance we insert a note after a new order is created.
Here is the way to approach this:
We will take over sale.order model. We will override the create() method. However, we won't totally replace the create() method. We will use super() to call original function. It is critical to use super(). After calling the original function using super() we add custom functionality.
from odoo import models, fields, api
class CustomSaleOrder(models.Model):
_inherit = 'sale.order'
@api.model
def create(self, vals):
# Call the super function to execute the original create method
order = super(CustomSaleOrder, self).create(vals)
# Add custom logic: add a note to the sale order
order.message_post(body="This order has been created with custom logic.")
# Return the order record created by the super function
return order
To test functionality follow steps provided:
Inheriting calling super function in Odoo can extend functionality. This can happen while retaining original behavior. Using super(), adding custom logic to methods is simple. This is key for tailoring Odoo to business needs without breaking core features.
In this blog, we learn to inherit create() method of the sale.order model. We add custom functionality. This pattern is useful for many other methods and models in Odoo. It is crucial for Odoo developers.
By following these steps extending Odoo's built-in methods is easy. This ensures that customizations stay compatible with future updates.
Your email address will not be published. Required fields are marked *