In certain situations, it becomes important to introduce additional
functionality to an existing Python method. This process is known as
method extension. When adding new features or customizing
existing model classes, it is often necessary to adjust or enhance
the current business logic. As a result, we may need to update
existing methods to support these new changes.
Let’s explore this concept through a practical example by extending a
custom method. Imagine we have a model that manages all student
records for a school.
from odoo import fields, models, api
class Student(models.Model):
_name = "student.student"
_description = "Student"
name = fields.Char(string="Name", required=True)
partner_id = fields.Many2one('res.partner', string="Partner")
phone = fields.Char(string="Phone Number")
email = fields.Char(string="Email", required=True)
status = fields.Char(string="Status")
Place a button on the student form view to change the value of the
student's status field.
<header>
<button name="update_status" string="Update Status" class="oe_highlight" type="object"/>
</header>
Create the update_status() method in the Python file, where the write
method is used to assign a new value to the status field of the
student record.
def update_status(self):
self.write({
'status': "Status Updated"
})
By inheriting the model, we can add a new date field named
date_status_last_updated to record the last time the student's
status was updated.
class StudentInherit(models.Model):
_inherit = "student.student"
date_status_last_updated = fields.Date(string="Status Updated Date")
By extending the update_status() method, we can also update the
date_status_last_updated field. To accomplish this, you should
define a method with the same name to extend the existing
functionality. The super() function can then be used to call the
original method from the parent class and execute its logic before
adding the new operations.
In Odoo, it is common practice to override methods like create() and
write() using super(). It is essential to ensure that when extending
a method, all parameters from the original method are included in
the extended version. Any additional arguments used in the parent
method must also be passed to the overridden method.
The following example demonstrates the correct way to extend a
method: it first performs all the actions from the parent method and
then proceeds with the additional custom logic.
def update_status(self):
res = super(Student, self).update_status()
self.write({
'date_status_last_updated': fields.Date.today()
})
return res
Overriding an existing method allows us to add new operations while
preserving its existing behavior.