官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 军事| 阜新市| 武冈市| 定结县| 临颍县| 法库县| 九台市| 会宁县| 青铜峡市| 陇川县| 武宣县| 阳谷县| 清原| 桂林市| 乌鲁木齐县| 左权县| 永川市| 尤溪县| 盐池县| 洛扎县| 遵义县| 安国市| 遂川县| 惠东县| 甘肃省| 庄浪县| 双鸭山市| 阿图什市| 延吉市| 伊宁市| 无为县| 平利县| 达孜县| 桃园市| 察隅县| 新绛县| 深水埗区| 双流县| 搜索| 垦利县| 玉溪市|