Přejít na obsah
Menu
You need to be registered to interact with the community.
This question has been flagged
1 Odpovědět
6479 Zobrazení

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.

Avatar
Zrušit
Autor Nejlepší odpověď
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)
Avatar
Zrušit
Related Posts Odpovědi Zobrazení Aktivita
1
zář 17
4877
0
srp 15
3446
0
srp 24
1481
1
čvn 23
3798
0
čvn 23
1686