Extending Python methods
The business logic that's coded into Python methods can also be extended. For this, Odoo borrows the mechanism that Python already provides for inherited objects to extend their parent class behavior.
As a practical example, we will extend the Library Book ISBN validation logic. The logic provided by the base Library app only validates modern 13-digit ISBNs, but some older titles might have a 10-digit ISBN. We will extend the
_check_isbn() method to also validate these cases.
Add this additional method in the
library_member/models/library_book.py file:from odoo import api, fields, models
class Book(models.Model):
_inherit = 'library.book'
is_available = fields.Boolean('Is Available?', readonly=False)
@api.multi
def _check_isbn(self):
self.ensure_one()
digits = [int(x) for x in self.isbn if x.isdigit()]
if len(digits) == 10:
ponderators = [1, 2, 3, 4, 5, 6, 7, 8, 9]
total = sum(a * b for a, b in zip(digits[:9], ponderators))
check = total % 11
return digits[-1] == check
else:
return super()._check_isbn()
To extend a method, we define it again, and at some point, can use
super() to call the method's existing implementation. In our method, we check whether it is a 10-digit ISBN, and in that case, perform the missing validation logic. Otherwise, we fall back to the original ISBN checking logic that can handle the 13-digit case.
If you want to try it, or even better, write a test case, here is an example of a 10-digit ISBN: 0-571-05686-5. It is the original ISBN of William Golding's Lord of the Flies.
Comments
Post a Comment