Bỏ qua để đến Nội dung
Menu
Câu hỏi này đã bị gắn cờ
1 Trả lời
6546 Lượt xem

Hi !

I try to show public categories on website only if they have products OR if they have child categories with products, recursively.

So, I thought it would be easy with api.depends and a stored computed Boolean field but it's not. This is my code:

@api.one
@api.depends('products', 'products.active', 'child_id', 'child_id.not_empty',
'child_id.products', 'child_id.products.active')
def _compute_not_empty(self):
self.not_empty = bool(self.products)
# avoid costly list build if already True
if not self.not_empty:
self.not_empty = any([p.not_empty for p in self.child_id])
_logger.info('not empty: {}: {}'.format(self.name, self.not_empty))

products = fields.Many2many('product.template')
not_empty = fields.Boolean(compute=_compute_not_empty, store=True)

Some categories react well when I set the active field of some products to False. But their parent categories don't always recompute...

A little help ?

**Edit:**

I tried this, with no more success:

@api.one
@api.depends('products')
def _compute_has_products(self):
self.has_products = bool(self.products)

@api.one
@api.depends('child_id', 'child_id.has_products', 'has_products')
def _compute_not_empty(self):
if self.has_products:
self.not_empty = True
elif not self.child_id:
self.not_empty = False
else:
for child in self.child_id:
if child.has_products:
self.not_empty = True
break

products = fields.Many2many('product.template')
has_products = fields.Boolean(store=True, compute=_compute_has_products)
not_empty = fields.Boolean(store=True, compute=_compute_not_empty)

Anyone has any idea how to successfully trigger upward computation of fields (child -> parent) ?

This seems to work up to the first parent of the category which initiated the computation, but no further.

Ảnh đại diện
Huỷ bỏ
Tác giả Câu trả lời hay nhất
class ProductPublicCategory(models.Model):
_inherit = 'product.public.category'

@api.one
@api.depends('products')
def _compute_has_products(self):
self.has_products = bool(self.products)

@api.one
@api.depends('child_id.not_empty', 'child_id')
def _compute_has_children(self):
if self.child_id:
for child in self.child_id:
if child.not_empty:
self.has_children = True
break
else:
self.has_children = False

@api.one
@api.depends('has_products', 'has_children')
def _compute_not_empty(self):
self.not_empty = self.has_products or self.has_children

products = fields.Many2many('product.template')
has_products = fields.Boolean(store=True, compute=_compute_has_products)
has_children = fields.Boolean(store=True, compute=_compute_has_children)
not_empty = fields.Boolean(store=True, compute=_compute_not_empty)
Ảnh đại diện
Huỷ bỏ
Bài viết liên quan Trả lời Lượt xem Hoạt động
1
thg 9 17
4931
0
thg 8 15
3533
0
thg 8 24
1568
1
thg 6 23
3927
0
thg 6 23
1738