How to do it...

We will add a new Python file, models/library_book_categ.py, for the category tree, as follows:

  1. To load the new Python code file, add the following line to models/__init__.py:
from . import library_book_categ
  1. To create the Book Category model with the parent and child relations, create the models/library_book_categ.py file with the following code:
from odoo import models, fields, api 
class BookCategory(models.Model): 
    _name = 'library.book.category' 
    name = fields.Char('Category') 
    parent_id = fields.Many2one( 
        'library.book.category', 
        string='Parent Category', 
        ondelete='restrict', 
        index=True) 
    child_ids = fields.One2many( 
        'library.book.category', 'parent_id', 
        string='Child Categories') 
  1. To enable the special hierarchy support, also add the following code:
_parent_store = True
_parent_name = "parent_id" # optional if field is 'parent_id'
parent_path = fields.Char(index=True)
  1. To add a check preventing looping relations, add the following line to the model:
from odoo.exceptions import ValidationError
...
@api.constrains('parent_id') def _check_hierarchy(self): if not self._check_recursion(): raise models.ValidationError( 'Error! You cannot create recursive categories.')

  1. Now, we need to assign a category to a book. To do this, we will add a new many2one field in the library.book model:
category_id = fields.Many2one('library.book.category')  

Finally, a module upgrade will make these changes effective.

To display the librart.book.category model in the user interface, you will need to add menus, views, and security rules. For more details, refer to Chapter 4, Creating Odoo Add-On Modules. Alternatively, you can access all code from https://github.com/PacktPublishing/Odoo-12-Development-Cookbook-Third-Edition.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset