Skip to Content
Menu
This question has been flagged
2884 Views

Hello,

I've created a model in a custom module. This model represents a tree structure. It's working quite good but I still have a bug that I can't figure out.

When the user changes the name, the complete_order field of its children is wrongly calculated.

For exemple the item with complete_name "Root Element / Child 1 / Child 1.1 / ... / Child n /  Last child" gets its complete_order like "False / Last child" if the name of the Child n is modified.

I had the same problem for complete_name that I solved by setting the stored property to false. As complete_order is used for the ordering of my items, I can't do the same and it looks like it has to be stored in db.

Any help appreciated !

Here is the code for my model :

# -*- coding: utf-8 -*-

from odoo import models, fields, api
from odoo.exceptions import ValidationError

class treeitem(models.Model):
_name = "mymodule.treeitem"
_description = "TreeItem"
_parent_name = "parent_id"
_parent_store = True
_rec_name = 'complete_name'
_order = 'complete_order'

name = fields.Char('Name', index=True, required=True, translate=True)
complete_name = fields.Char(
'Complete Name', compute='_compute_complete_name',
store=False)
complete_order = fields.Char(
'Complete Order', compute='_compute_complete_order',
store=True)

parent_id = fields.Many2one('mymodule.treeitem', 'Parent Item', index=True, ondelete='cascade')
parent_path = fields.Char(index=True)
child_id = fields.One2many('mymodule.treeitem', 'parent_id', 'Child Items')
order = fields.Integer(default=0)

information = fields.Text()

@api.depends('name', 'parent_id.complete_name')
def _compute_complete_name(self):
for item in self:
if item.parent_id:
item.complete_name = '%s / %s' % (item.parent_id.complete_name, item.name)
else:
item.complete_name = item.name

@api.depends('name', 'order', 'parent_id.complete_order')
def _compute_complete_order(self):
for item in self:
if item.parent_id:
item.complete_order = '%s / %04d-%s' % (item.parent_id.complete_order, item.order, item.name)
else:
item.complete_order = '%04d-%s' % (item.order, item.name)

@api.constrains('parent_id')
def _check_item_recursion(self):
if not self._check_recursion():
raise ValidationError(_('You cannot create recursive categories.'))
return True

Thank you !



Avatar
Discard

Hi

You can refer how name is computed for stock.location.

Thanks,