- Odoo 11 Development Cookbook(Second Edition)
- Holger Brunn Alexandre Fayolle
- 140字
- 2021-06-25 22:48:49
How to do it...
We will add a new Python file, models/library_book_categ.py, for the category tree, shown as follows:
- To have the new Python code file loaded, add this line to models/__init__.py:
from . import library_book_categ
- To create the Book Category model with the parent and child relations, create the models/library_book_categ.py file with the following:
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')
- To enable the special hierarchy support, also add the following:
_parent_store = True parent_left = fields.Integer(index=True) parent_right = fields.Integer(index=True)
- To add a check preventing looping relations, add the following line to the model:
@api.constrains('parent_id') def _check_hierarchy(self): if not self._check_recursion(): raise models.ValidationError( 'Error! You cannot create recursive categories.')
Finally, a module upgrade will make these changes effective.