From 9ddd96d938d9ed170cfbc93e3175d582c902a868 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Iv=C3=A0n=20Todorovich?= Date: Thu, 30 Jun 2022 15:46:33 -0300 Subject: [PATCH] [IMP] product_category_tax: set tax performance on large recordsets 1) database searching is much more efficient than py filtering 2) writing on multiple products at once is more efficient --- product_category_tax/models/product_category.py | 13 +++++++++---- product_category_tax/models/product_product.py | 4 +--- product_category_tax/models/product_template.py | 16 +++++++++++++--- 3 files changed, 23 insertions(+), 10 deletions(-) diff --git a/product_category_tax/models/product_category.py b/product_category_tax/models/product_category.py index 23f269912..b1ee87b76 100644 --- a/product_category_tax/models/product_category.py +++ b/product_category_tax/models/product_category.py @@ -32,7 +32,12 @@ class ProductCategory(models.Model): ) def update_product_taxes(self): - for template in self.product_template_ids.filtered( - lambda p: p.taxes_updeatable_from_category - ): - template.set_tax_from_category() + products = self.env["product.template"].search( + [ + ("categ_id", "in", self.ids), + ("taxes_updeatable_from_category", "=", True), + ] + ) + if not products: + return True + return products.set_tax_from_category() diff --git a/product_category_tax/models/product_product.py b/product_category_tax/models/product_product.py index afc712d47..1b7f70a33 100644 --- a/product_category_tax/models/product_product.py +++ b/product_category_tax/models/product_product.py @@ -13,6 +13,4 @@ class ProductProduct(models.Model): self.set_tax_from_category() def set_tax_from_category(self): - self.ensure_one() - self.taxes_id = [(6, 0, self.categ_id.taxes_id.ids)] - self.supplier_taxes_id = [(6, 0, self.categ_id.supplier_taxes_id.ids)] + return self.product_tmpl_id.set_tax_from_category() diff --git a/product_category_tax/models/product_template.py b/product_category_tax/models/product_template.py index 23bdb69f2..2a7c4b836 100644 --- a/product_category_tax/models/product_template.py +++ b/product_category_tax/models/product_template.py @@ -1,6 +1,8 @@ # Copyright 2020 ForgeFlow S.L. (https://www.forgeflow.com) # License LGPL-3.0 or later (http://www.gnu.org/licenses/lgpl.html). +from collections import defaultdict + from odoo import api, fields, models @@ -15,6 +17,14 @@ class ProductTemplate(models.Model): self.set_tax_from_category() def set_tax_from_category(self): - self.ensure_one() - self.taxes_id = [(6, 0, self.categ_id.taxes_id.ids)] - self.supplier_taxes_id = [(6, 0, self.categ_id.supplier_taxes_id.ids)] + records_by_categ = defaultdict(lambda: self.browse()) + for rec in self: + records_by_categ[rec.categ_id] += rec + for categ, records in records_by_categ.items(): + records.write( + { + "taxes_id": [(6, 0, categ.taxes_id.ids)], + "supplier_taxes_id": [(6, 0, categ.supplier_taxes_id.ids)], + } + ) + return True