【示例】“全名”字段显示完整的层级名称,例如:“一级分类 / 二级分类 / 三级分类”。
name = fields.Char(
'名称',
index=True,
required=True
)
complete_name = fields.Char(
'全名',
compute='_compute_complete_name',
store=True
)
parent_id = fields.Many2one(
'product.category',
'父分类',
index=True,
ondelete='cascade'
)
@api.depends('name', 'parent_id.complete_name')
def _compute_complete_name(self):
for category in self:
if category.parent_id:
category.complete_name = '%s / %s' % (category.parent_id.complete_name, category.name)
else:
category.complete_name = category.name
【示例】计算产品品类下的产品数量。
product_count = fields.Integer(
'# Products', compute='_compute_product_count',
help="此类别下的产品数量(不考虑子类别)"
)
def _compute_product_count(self):
read_group_res = self.env['product.template'].read_group([('categ_id', 'child_of', self.ids)], ['categ_id'], ['categ_id'])
group_data = dict((data['categ_id'][0], data['categ_id_count']) for data in read_group_res)
for categ in self:
product_count = 0
for sub_categ_id in categ.search([('id', 'child_of', categ.ids)]).ids:
product_count += group_data.get(sub_categ_id, 0)
categ.product_count = product_count