I have a function that looks up one id and compares it to another, after that it looks up that id in a list, however sometimes the last & penultimate record might be zero , so I would like to get the last non-zero record
Here is the function:
@api.one
@api.depends('seller_ids')
def _costo_anterior(self):
_logger = logging.getLogger(__name__)
if self.default_code or self.default_code !='':
product_search = self.env['product.product'].search([('default_code', '=',self.default_code)],limit = 1)
all_seller_ids = product_search.seller_ids.ids
_logger.info('seller_ids: %s', all_seller_ids)
if all_seller_ids:
id_ultimo_costo = all_seller_ids[-1]
supplier = self.env['product.supplierinfo'].search([('id', '=', id_ultimo_costo)])
self.costo_anterior = supplier.price
_logger.info('Costo anterior: %s', self.costo_anterior)
if self.costo_anterior == 0.0 and len(all_seller_ids) > 1:
id_ultimo_costo = all_seller_ids[-2]
supplier = self.env['product.supplierinfo'].search([('id', '=', id_ultimo_costo)])
self.costo_anterior = supplier.price
else:
_logger.info('Solo tiene un registro')
else:
self.costo_anterior = 0.0
You can use a function like this:
which returns the last non-zero element of the list, or zero if the list is empty or has no distinct values.
The trick is to iterate through the list in reverse order, which is achieved with
lista[::-1]
, which reverses it.Then it is a matter of returning with the first non-zero value.
show
produces: