feat: Optimize lot/serial number search by directly querying quants for specific locations and products when restricting by source.

This commit is contained in:
Suherdy Yacob 2026-03-05 14:05:06 +07:00
parent a0a0b81ec6
commit 9a9ce14ccf

View File

@ -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)