Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Improve attribute fetching in AttributeAssignmentMixin (#18616) (#18632)
Iga Karbowiak98b4e5ae5d20
diff --git a/saleor/graphql/attribute/utils/attribute_assignment.py b/saleor/graphql/attribute/utils/attribute_assignment.pyindex 1d0018acfe..0aa65de9f5 100644--- a/saleor/graphql/attribute/utils/attribute_assignment.py+++ b/saleor/graphql/attribute/utils/attribute_assignment.py@@ -3,7 +3,7 @@ from typing import TYPE_CHECKING, castimport graphenefrom django.core.exceptions import ValidationError-from django.db.models import Q+from django.db.models import Prefetch, Qfrom django.db.models.expressions import Exists, OuterReffrom graphql.error import GraphQLError@@ -11,6 +11,7 @@ from ....attribute import AttributeInputTypefrom ....attribute import models as attribute_modelsfrom ....attribute.models import AttributeValuefrom ....attribute.utils import associate_attribute_values_to_instance+from ....page import models as page_modelsfrom ....page.error_codes import PageErrorCodefrom ....product import models as product_modelsfrom ....product.error_codes import ProductErrorCode@@ -79,7 +80,16 @@ class AttributeAssignmentMixin:Q(pk__in=id_map.keys()) | Q(external_reference__in=ext_ref_set))nodes = list(- nodes.prefetch_related("reference_product_types", "reference_page_types")+ nodes.prefetch_related(+ Prefetch(+ "reference_product_types",+ queryset=product_models.ProductType.objects.only("id"),+ ),+ Prefetch(+ "reference_page_types",+ queryset=page_models.PageType.objects.only("id"),+ ),+ ))resolved_pks = {node.pk for node in nodes}@@ -98,6 +108,16 @@ class AttributeAssignmentMixin:)return nodes+ @classmethod+ def _clear_prefetch_cache(cls, attributes: list[attribute_models.Attribute]):+ """Clear prefetched objects cache.++ After validation is complete, the prefetched relations are no longer needed.+ """+ for attribute in attributes:+ if hasattr(attribute, "_prefetched_objects_cache"):+ attribute._prefetched_objects_cache.clear()+@classmethoddef clean_input(cls,@@ -129,6 +149,9 @@ class AttributeAssignmentMixin:creation,)+ # Clear prefetched cache after validation to prevent memory leaks+ cls._clear_prefetch_cache(attributes)+return cleaned_input@classmethod