From c837adc236f2abb2aa2f8d0ed88f9a1ec702baf4 Mon Sep 17 00:00:00 2001 From: Guewen Baconnier Date: Fri, 15 May 2020 12:16:32 +0200 Subject: [PATCH] Optimize SQL queries when searching a rule Searching all rules then filtering in python the parent path is more efficient than finding all the parent locations and finding the matching rules. --- stock_reserve_rule/models/stock_reserve_rule.py | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/stock_reserve_rule/models/stock_reserve_rule.py b/stock_reserve_rule/models/stock_reserve_rule.py index add61e828..e794e999a 100644 --- a/stock_reserve_rule/models/stock_reserve_rule.py +++ b/stock_reserve_rule/models/stock_reserve_rule.py @@ -82,7 +82,14 @@ class StockReserveRule(models.Model): raise ValidationError(msg) def _rules_for_location(self, location): - return self.search([("location_id", "parent_of", location.id)]) + # We'll typically have a handful of rules, so reading all of them then + # checking if they are a parent location of the location is pretty + # fast. Searching all the parent locations then the rules matching them + # can be much slower if we have many locations. + rules = self.search([]).filtered( + lambda rule: rule.location_id.parent_path.startswith(location.parent_path) + ) + return rules def _eval_rule_domain(self, move, domain): move_domain = [("id", "=", move.id)]