Skip to content

Saleor Core: the high performance, composable, headless commerce API.

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.py
index 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, cast
import graphene
from django.core.exceptions import ValidationError
-from django.db.models import Q
+from django.db.models import Prefetch, Q
from django.db.models.expressions import Exists, OuterRef
from graphql.error import GraphQLError
@@ -11,6 +11,7 @@ from ....attribute import AttributeInputType
from ....attribute import models as attribute_models
from ....attribute.models import AttributeValue
from ....attribute.utils import associate_attribute_values_to_instance
+from ....page import models as page_models
from ....page.error_codes import PageErrorCode
from ....product import models as product_models
from ....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()
+
@classmethod
def 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