Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Fix performance of update_variant_names (#10657)
Tomasz Szymański926c2629f96d
diff --git a/saleor/product/tasks.py b/saleor/product/tasks.pyindex 2426d3a4d6..0ebe6625f8 100644--- a/saleor/product/tasks.py+++ b/saleor/product/tasks.py@@ -24,6 +24,8 @@ from .utils.variants import generate_and_set_variant_namelogger = logging.getLogger(__name__)task_logger = get_task_logger(__name__)+VARIANTS_UPDATE_BATCH = 500+def _update_variants_names(instance: ProductType, saved_attributes: Iterable):"""Product variant names are created from names of assigned attributes.@@ -35,15 +37,23 @@ def _update_variants_names(instance: ProductType, saved_attributes: Iterable):attributes_changed = initial_attributes.intersection(saved_attributes)if not attributes_changed:return- variants_to_be_updated = ProductVariant.objects.filter(++ variants = ProductVariant.objects.filter(product__in=instance.products.all(),product__product_type__variant_attributes__in=attributes_changed,)- variants_to_be_updated = variants_to_be_updated.prefetch_related(- "attributes__values__translations"- ).all()- for variant in variants_to_be_updated:- generate_and_set_variant_name(variant, variant.sku)++ variants_to_update = []+ for variant in variants:+ variants_to_update.append(+ generate_and_set_variant_name(variant, variant.sku, save=False)+ )+ if len(variants_to_update) > VARIANTS_UPDATE_BATCH:+ ProductVariant.objects.bulk_update(+ variants_to_update, ["name", "updated_at"]+ )+ variants_to_update = []+ ProductVariant.objects.bulk_update(variants_to_update, ["name", "updated_at"])@app.taskdiff --git a/saleor/product/utils/variants.py b/saleor/product/utils/variants.pyindex 3aa81dd22b..b13cb4f3f3 100644--- a/saleor/product/utils/variants.py+++ b/saleor/product/utils/variants.py@@ -7,7 +7,9 @@ if TYPE_CHECKING:from ..models import ProductVariant-def generate_and_set_variant_name(variant: "ProductVariant", sku: Optional[str]):+def generate_and_set_variant_name(+ variant: "ProductVariant", sku: Optional[str], save: Optional[bool] = True+):"""Generate ProductVariant's name based on its attributes."""attributes_display = []@@ -27,7 +29,9 @@ def generate_and_set_variant_name(variant: "ProductVariant", sku: Optional[str])name = sku or variant.get_global_id()variant.name = name- variant.save(update_fields=["name", "updated_at"])+ if save:+ variant.save(update_fields=["name", "updated_at"])+ return variantdef get_variant_selection_attributes(