- Odoo 12 Development Essentials
- Daniel Reis
- 436字
- 2021-07-02 14:18:49
Adding business logic
Previously, we added a button to the Book Form section to check whether the ISBN is valid. Modern ISBNs have 13 digits, where the last one is a check digit computed from the first 12.
There is little point getting into the details of the algorithm used, so here is a Python function that implements this validation. It should be added inside the class Book(...) object, before the name field:
@api.multi
def _check_isbn(self):
self.ensure_one()
digits = [int(x) for x in self.isbn if x.isdigit()]
if len(digits) == 13:
ponderations = [1, 3] * 6
terms = [a * b for a, b in zip(digits[:12], ponderations)]
remain = sum(terms) % 10
check = 10 - remain if remain != 0 else 0
return digits[-1] == check
The button_check_isbn() method of the Book model should use this function to validate the number in the ISBN field. If the validation fails, we should present the users with a warning message.
First, we need to import the Odoo API library, adding the corresponding import, as well as the Odoo Warning exception. To do this, we need to edit the library_book.py Python file so that these are the first lines of the file:
from odoo import api, fields, models
from odoo.exceptions import Warning
Next, still in the models/library_book.py file, add the following to the Book class:
@api.multi
def button_check_isbn(self): for book in self: if not book.isbn:
raise Warning('Please provide an ISBN for %s' % book.name)
if book.isbn and not book._check_isbn():
raise Warning('%s is an invalid ISBN' % book.isbn) return True
For logic on records, we use the @api.multi decorator. Here, self will represent a recordset, and we should then loop through each record. In fact, this is the default for model methods, so the @api.multi decorator could be safely omitted here. We prefer to keep it for clarity.
The code loops through all the selected Book task records and, for each one, if the Book ISBN has a value, it checks whether it is a valid ISBN. If not, a warning message is raised for the user.
The Model method does not need to return anything, but we should have it at least return a True value. The reason is that not all client implementations of the XML-RPC protocol support None/Null values, and may raise errors when such a value is returned by a method.
This a good moment to upgrade the module and run the tests again, adding the --test-enable option to confirm that tests are now passing. You can also try it live, going into a Book Form and trying the button with both correct and incorrect ISBNs.