From 9a9ce14ccff051f975057ca7f5de332d521d592b Mon Sep 17 00:00:00 2001 From: Suherdy Yacob Date: Thu, 5 Mar 2026 14:05:06 +0700 Subject: [PATCH] feat: Optimize lot/serial number search by directly querying quants for specific locations and products when restricting by source. --- models/stock_location.py | 22 ++++++++++++++++------ 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/models/stock_location.py b/models/stock_location.py index 17e6c04..e34c834 100644 --- a/models/stock_location.py +++ b/models/stock_location.py @@ -138,16 +138,26 @@ class StockLot(models.Model): loc_id = ctx.get('default_location_id') if active_picking_id and loc_id: - picking = self.env['stock.picking'].sudo().browse(active_picking_id) loc = self.env['stock.location'].sudo().browse(loc_id) # If the source is an internal or transit location, restrict the dropdown to lots actually present there. # If the source is a supplier, we do not filter (they could be receiving brand new lots). - if picking.exists() and loc.exists() and loc.usage != 'supplier': - domain = Domain.AND([domain, [ - ('quant_ids.location_id', 'child_of', loc.id), - ('quant_ids.quantity', '>', 0) - ]]) + if loc.exists() and loc.usage != 'supplier': + quant_domain = [ + ('location_id', 'child_of', loc.id), + ('quantity', '>', 0), + ('lot_id', '!=', False) + ] + + # Highly optimized query: only search quants for the specific product + product_id = ctx.get('default_product_id') + if product_id: + quant_domain.append(('product_id', '=', product_id)) + + quants = self.env['stock.quant'].sudo().search(quant_domain) + lot_ids = list(set(quants.mapped('lot_id').ids)) + + domain = Domain.AND([domain, [('id', 'in', lot_ids)]]) return super()._search(domain, offset=offset, limit=limit, order=order, *args, **kwargs)