I'm making a function in Odoo 15 which takes the records from a table called product_supplierinfo , takes the cost value and assigns it to a field called previous_cost , however sometimes the last record is zero so the function should take the value before that, that is, the penultimate one & so on until it finds a non-zero value.
I already have a function that does it, however, I don't think it will be as functional when there are more than 5 or 6 records.
Here is the function I mentioned earlier:
@api.depends('seller_ids')
def _previous_cost(self):
self.ensure_one()
_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 len(all_seller_ids) < 1:
self.previous_cost = 0.0
else:
if all_seller_ids:
id_ultimo_costo = all_seller_ids[-1]
supplier = self.env['product.supplierinfo'].search([('id', '=', id_ultimo_costo)])
self.previous_cost = supplier.price
_logger.info('Costo anterior: %s', self.previous_cost)
if len(all_seller_ids) > 1:
if self.previous_cost == 0.0:
id_ultimo_costo = all_seller_ids[-2]
supplier = self.env['product.supplierinfo'].search([('id', '=', id_ultimo_costo)])
self.previous_cost = supplier.price
_logger.info('Costo anterior: %s', self.previous_cost)
if len(all_seller_ids) > 2:
if self.previous_cost == 0.0:
id_ultimo_costo = all_seller_ids[-3]
supplier = self.env['product.supplierinfo'].search([('id', '=', id_ultimo_costo)])
self.previous_cost = supplier.price
_logger.info('Costo anterior: %s', self.previous_cost)
else:
_logger.info('Registro [-3] no es igual a 0.0')
else:
self.previous_cost = 0.0
else:
self.previous_cost = 0.0
else:
self.previous_cost = 0.0
else:
self.previous_cost = 0.0
Thank you very much for your time.
I don't know much about
odoo
, but it would be easier to do the proper query.That is, you have something like this
At first glance we can see that what you need is only the value
400
, since from back to front.So we just have to do
If you do this query to yourself, it
db
should bring you a single record that would beNow in
Oddo
you would have to simply do something likeNOTE As I mentioned, I don't know much about it
odoo
but in any case it would only be to adjustTo the correct form if this brings you a fix
supplier[0]
or if something fails, adapt it to the previous query.