Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Delete detached FILE attribute values in object update mutations so clients no longer need the permission-restricted attributeValueDelete to clean up after replacing or clearing a file (#19709) (#19722)
Marcin Wcisłoe6a01b6a5cb5
diff --git a/saleor/graphql/attribute/tests/mutations/test_file_value_cleanup.py b/saleor/graphql/attribute/tests/mutations/test_file_value_cleanup.pynew file mode 100644index 0000000000..283d148f72--- /dev/null+++ b/saleor/graphql/attribute/tests/mutations/test_file_value_cleanup.py@@ -0,0 +1,721 @@+from unittest import mock++import graphene+from django.conf import settings++from .....attribute import AttributeInputType, AttributeType+from .....attribute.models import (+ AssignedPageAttributeValue,+ AssignedProductAttributeValue,+ AssignedVariantAttributeValue,+ Attribute,+ AttributeValue,+)+from .....attribute.utils import associate_attribute_values_to_instance+from .....product.models import Product+from ....tests.utils import get_graphql_content++PRODUCT_UPDATE_MUTATION = """+ mutation ProductUpdate($productId: ID!, $input: ProductInput!) {+ productUpdate(id: $productId, input: $input) {+ errors {+ field+ code+ message+ }+ }+ }+"""++VARIANT_UPDATE_MUTATION = """+ mutation VariantUpdate($id: ID!, $attributes: [AttributeValueInput!]) {+ productVariantUpdate(id: $id, input: {attributes: $attributes}) {+ errors {+ field+ code+ message+ }+ }+ }+"""++VARIANT_BULK_UPDATE_MUTATION = """+ mutation VariantBulkUpdate(+ $productId: ID!, $variants: [ProductVariantBulkUpdateInput!]!+ ) {+ productVariantBulkUpdate(product: $productId, variants: $variants) {+ count+ results {+ errors {+ field+ code+ message+ }+ }+ }+ }+"""++PAGE_UPDATE_MUTATION = """+ mutation PageUpdate($id: ID!, $attributes: [AttributeValueInput!]) {+ pageUpdate(id: $id, input: {attributes: $attributes}) {+ errors {+ field+ code+ message+ }+ }+ }+"""++CUSTOMER_UPDATE_MUTATION = """+ mutation CustomerUpdate($id: ID!, $attributes: [AttributeValueInput!]) {+ customerUpdate(id: $id, input: {attributes: $attributes}) {+ errors {+ field+ code+ message+ }+ }+ }+"""+++def build_file_url(file_name):+ return f"https://example.com{settings.MEDIA_URL}{file_name}"+++class RollbackTrigger(Exception):+ pass+++def test_replace_deletes_previous_value(+ staff_api_client,+ product,+ product_type,+ file_attribute,+ permission_manage_products,+):+ # given+ product_type.product_attributes.add(file_attribute)+ old_value = file_attribute.values.first()+ unassigned_sibling_value = file_attribute.values.last()+ associate_attribute_values_to_instance(product, {file_attribute.pk: [old_value]})++ file_name = "new_file.jpg"+ variables = {+ "productId": graphene.Node.to_global_id("Product", product.pk),+ "input": {+ "attributes": [+ {+ "id": graphene.Node.to_global_id("Attribute", file_attribute.pk),+ "file": build_file_url(file_name),+ }+ ]+ },+ }++ # when+ response = staff_api_client.post_graphql(+ PRODUCT_UPDATE_MUTATION, variables, permissions=[permission_manage_products]+ )++ # then+ content = get_graphql_content(response)+ assert content["data"]["productUpdate"]["errors"] == []++ assert AttributeValue.objects.filter(pk=old_value.pk).exists() is False+ new_value = AssignedProductAttributeValue.objects.get(+ product=product, value__attribute=file_attribute+ ).value+ assert new_value.file_url == file_name++ # ensure sibling vales is untouched+ assert AttributeValue.objects.filter(pk=unassigned_sibling_value.pk).exists()+++def test_clear_deletes_previous_value(+ staff_api_client,+ product,+ product_type,+ file_attribute,+ permission_manage_products,+):+ # given+ product_type.product_attributes.add(file_attribute)+ old_value = file_attribute.values.first()+ associate_attribute_values_to_instance(product, {file_attribute.pk: [old_value]})++ variables = {+ "productId": graphene.Node.to_global_id("Product", product.pk),+ "input": {+ "attributes": [+ {+ "id": graphene.Node.to_global_id("Attribute", file_attribute.pk),+ "file": None,+ }+ ]+ },+ }++ # when+ response = staff_api_client.post_graphql(+ PRODUCT_UPDATE_MUTATION, variables, permissions=[permission_manage_products]+ )++ # then+ content = get_graphql_content(response)+ assert content["data"]["productUpdate"]["errors"] == []++ assert AttributeValue.objects.filter(pk=old_value.pk).exists() is False+ assert (+ AssignedProductAttributeValue.objects.filter(+ product=product, value__attribute=file_attribute+ ).exists()+ is False+ )+++def test_same_file_url_keeps_the_value(+ staff_api_client,+ product,+ product_type,+ file_attribute,+ permission_manage_products,+):+ # given+ product_type.product_attributes.add(file_attribute)+ old_value = file_attribute.values.first()+ associate_attribute_values_to_instance(product, {file_attribute.pk: [old_value]})+ values_count = file_attribute.values.count()++ variables = {+ "productId": graphene.Node.to_global_id("Product", product.pk),+ "input": {+ "attributes": [+ {+ "id": graphene.Node.to_global_id("Attribute", file_attribute.pk),+ "file": build_file_url(old_value.file_url),+ }+ ]+ },+ }++ # when+ response = staff_api_client.post_graphql(+ PRODUCT_UPDATE_MUTATION, variables, permissions=[permission_manage_products]+ )++ # then+ content = get_graphql_content(response)+ assert content["data"]["productUpdate"]["errors"] == []++ assigned_value = AssignedProductAttributeValue.objects.get(+ product=product, value__attribute=file_attribute+ ).value+ assert assigned_value == old_value+ assert file_attribute.values.count() == values_count+++def test_failed_mutation_rolls_back_the_delete(+ staff_api_client,+ product_with_variant_with_file_attribute,+ file_attribute,+ permission_manage_products,+):+ """A failure after the attribute save must also roll the delete back.++ On productVariantUpdate the product row is saved after the attributes,+ inside the same transaction, so failing that save exercises the rollback+ through the real mutation.+ """+ # given+ variant = product_with_variant_with_file_attribute.variants.first()+ old_value = AssignedVariantAttributeValue.objects.get(+ assignment__variant=variant, value__attribute=file_attribute+ ).value+ values_count = file_attribute.values.count()++ variables = {+ "id": graphene.Node.to_global_id("ProductVariant", variant.pk),+ "attributes": [+ {+ "id": graphene.Node.to_global_id("Attribute", file_attribute.pk),+ "file": build_file_url("new_file.jpg"),+ }+ ],+ }++ # when+ with mock.patch.object(Product, "save", side_effect=RollbackTrigger("injected")):+ response = staff_api_client.post_graphql(+ VARIANT_UPDATE_MUTATION, variables, permissions=[permission_manage_products]+ )++ # then+ content = get_graphql_content(response, ignore_errors=True)+ assert len(content["errors"]) == 1+ assert content["data"]["productVariantUpdate"] is None++ assert AttributeValue.objects.filter(pk=old_value.pk).exists()+ assigned_value = AssignedVariantAttributeValue.objects.get(+ assignment__variant=variant, value__attribute=file_attribute+ ).value+ assert assigned_value == old_value+ assert file_attribute.values.count() == values_count+++def test_value_assigned_to_another_entity_is_kept(+ staff_api_client,+ product,+ product_type,+ file_attribute,+ page,+ permission_manage_products,+):+ # given a legacy-shaped value shared between a product and a page+ product_type.product_attributes.add(file_attribute)+ old_value = file_attribute.values.first()+ associate_attribute_values_to_instance(product, {file_attribute.pk: [old_value]})+ page_assignment = AssignedPageAttributeValue.objects.create(+ page=page, value=old_value+ )+ values_count = file_attribute.values.count()++ variables = {+ "productId": graphene.Node.to_global_id("Product", product.pk),+ "input": {+ "attributes": [+ {+ "id": graphene.Node.to_global_id("Attribute", file_attribute.pk),+ "file": None,+ }+ ]+ },+ }++ # when+ response = staff_api_client.post_graphql(+ PRODUCT_UPDATE_MUTATION, variables, permissions=[permission_manage_products]+ )++ # then+ content = get_graphql_content(response)+ assert content["data"]["productUpdate"]["errors"] == []++ assert (+ AssignedProductAttributeValue.objects.filter(+ product=product, value__attribute=file_attribute+ ).exists()+ is False+ )+ assert AttributeValue.objects.filter(pk=old_value.pk).exists()+ assert AssignedPageAttributeValue.objects.filter(pk=page_assignment.pk).exists()+ # clearing must not create any new value either+ assert file_attribute.values.count() == values_count+++def test_swatch_values_are_kept(+ staff_api_client,+ product,+ product_type,+ swatch_attribute,+ permission_manage_products,+):+ # given+ product_type.product_attributes.add(swatch_attribute)+ old_choice = swatch_attribute.values.first()+ new_choice = swatch_attribute.values.last()+ associate_attribute_values_to_instance(product, {swatch_attribute.pk: [old_choice]})++ variables = {+ "productId": graphene.Node.to_global_id("Product", product.pk),+ "input": {+ "attributes": [+ {+ "id": graphene.Node.to_global_id("Attribute", swatch_attribute.pk),+ "swatch": {+ "id": graphene.Node.to_global_id(+ "AttributeValue", new_choice.pk+ )+ },+ }+ ]+ },+ }++ # when+ response = staff_api_client.post_graphql(+ PRODUCT_UPDATE_MUTATION, variables, permissions=[permission_manage_products]+ )++ # then swatch choices are attribute definition rows and must survive+ content = get_graphql_content(response)+ assert content["data"]["productUpdate"]["errors"] == []++ assert AttributeValue.objects.filter(pk=old_choice.pk).exists()+ assigned_value = AssignedProductAttributeValue.objects.get(+ product=product, value__attribute=swatch_attribute+ ).value+ assert assigned_value == new_choice+++def test_attribute_absent_from_input_is_kept(+ staff_api_client,+ product,+ product_type,+ file_attribute,+ permission_manage_products,+):+ # given a second file attribute that the input does not touch+ other_file_attribute = Attribute.objects.create(+ slug="manual",+ name="Manual",+ type=AttributeType.PRODUCT_TYPE,+ input_type=AttributeInputType.FILE,+ )+ other_value = AttributeValue.objects.create(+ attribute=other_file_attribute,+ name="manual.pdf",+ slug="manualpdf",+ file_url="manual.pdf",+ )+ product_type.product_attributes.add(file_attribute, other_file_attribute)+ old_value = file_attribute.values.first()+ associate_attribute_values_to_instance(+ product,+ {file_attribute.pk: [old_value], other_file_attribute.pk: [other_value]},+ )++ file_name = "new_file.jpg"+ variables = {+ "productId": graphene.Node.to_global_id("Product", product.pk),+ "input": {+ "attributes": [+ {+ "id": graphene.Node.to_global_id("Attribute", file_attribute.pk),+ "file": build_file_url(file_name),+ }+ ]+ },+ }++ # when+ response = staff_api_client.post_graphql(+ PRODUCT_UPDATE_MUTATION, variables, permissions=[permission_manage_products]+ )++ # then+ content = get_graphql_content(response)+ assert content["data"]["productUpdate"]["errors"] == []++ assert AttributeValue.objects.filter(pk=old_value.pk).exists() is False+ new_value = AssignedProductAttributeValue.objects.get(+ product=product, value__attribute=file_attribute+ ).value+ assert new_value.file_url == file_name+ assert AttributeValue.objects.filter(pk=other_value.pk).exists()+ assert AssignedProductAttributeValue.objects.filter(+ product=product, value=other_value+ ).exists()+++def test_clear_deletes_all_assigned_values(+ staff_api_client,+ product,+ product_type,+ file_attribute,+ permission_manage_products,+):+ # given a legacy shape with two values assigned for one file attribute+ product_type.product_attributes.add(file_attribute)+ first_value = file_attribute.values.first()+ second_value = file_attribute.values.last()+ associate_attribute_values_to_instance(+ product, {file_attribute.pk: [first_value, second_value]}+ )++ variables = {+ "productId": graphene.Node.to_global_id("Product", product.pk),+ "input": {+ "attributes": [+ {+ "id": graphene.Node.to_global_id("Attribute", file_attribute.pk),+ "file": None,+ }+ ]+ },+ }++ # when+ response = staff_api_client.post_graphql(+ PRODUCT_UPDATE_MUTATION, variables, permissions=[permission_manage_products]+ )++ # then+ content = get_graphql_content(response)+ assert content["data"]["productUpdate"]["errors"] == []++ assert file_attribute.values.exists() is False+ assert (+ AssignedProductAttributeValue.objects.filter(+ product=product, value__attribute=file_attribute+ ).exists()+ is False+ )+++def test_variant_replace_deletes_previous_value(+ staff_api_client,+ product_with_variant_with_file_attribute,+ file_attribute,+ permission_manage_products,+):+ # given+ variant = product_with_variant_with_file_attribute.variants.first()+ old_value = AssignedVariantAttributeValue.objects.get(+ assignment__variant=variant, value__attribute=file_attribute+ ).value++ file_name = "new_file.jpg"+ variables = {+ "id": graphene.Node.to_global_id("ProductVariant", variant.pk),+ "attributes": [+ {+ "id": graphene.Node.to_global_id("Attribute", file_attribute.pk),+ "file": build_file_url(file_name),+ }+ ],+ }++ # when+ response = staff_api_client.post_graphql(+ VARIANT_UPDATE_MUTATION, variables, permissions=[permission_manage_products]+ )++ # then+ content = get_graphql_content(response)+ assert content["data"]["productVariantUpdate"]["errors"] == []++ assert AttributeValue.objects.filter(pk=old_value.pk).exists() is False+ new_value = AssignedVariantAttributeValue.objects.get(+ assignment__variant=variant, value__attribute=file_attribute+ ).value+ assert new_value.file_url == file_name+++def test_variant_clear_deletes_previous_value(+ staff_api_client,+ product_with_variant_with_file_attribute,+ file_attribute,+ permission_manage_products,+):+ # given+ variant = product_with_variant_with_file_attribute.variants.first()+ old_value = AssignedVariantAttributeValue.objects.get(+ assignment__variant=variant, value__attribute=file_attribute+ ).value++ variables = {+ "id": graphene.Node.to_global_id("ProductVariant", variant.pk),+ "attributes": [+ {+ "id": graphene.Node.to_global_id("Attribute", file_attribute.pk),+ "file": None,+ }+ ],+ }++ # when+ response = staff_api_client.post_graphql(+ VARIANT_UPDATE_MUTATION, variables, permissions=[permission_manage_products]+ )++ # then+ content = get_graphql_content(response)+ assert content["data"]["productVariantUpdate"]["errors"] == []++ assert AttributeValue.objects.filter(pk=old_value.pk).exists() is False+ assert (+ AssignedVariantAttributeValue.objects.filter(+ assignment__variant=variant, value__attribute=file_attribute+ ).exists()+ is False+ )+++def test_variant_bulk_update_replace_deletes_previous_value(+ staff_api_client,+ product_with_variant_with_file_attribute,+ file_attribute,+ permission_manage_products,+):+ # given+ product = product_with_variant_with_file_attribute+ variant = product.variants.first()+ old_value = AssignedVariantAttributeValue.objects.get(+ assignment__variant=variant, value__attribute=file_attribute+ ).value++ file_name = "new_file.jpg"+ variables = {+ "productId": graphene.Node.to_global_id("Product", product.pk),+ "variants": [+ {+ "id": graphene.Node.to_global_id("ProductVariant", variant.pk),+ "attributes": [+ {+ "id": graphene.Node.to_global_id(+ "Attribute", file_attribute.pk+ ),+ "file": build_file_url(file_name),+ }+ ],+ }+ ],+ }++ # when+ response = staff_api_client.post_graphql(+ VARIANT_BULK_UPDATE_MUTATION,+ variables,+ permissions=[permission_manage_products],+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["productVariantBulkUpdate"]+ assert data["count"] == 1+ assert data["results"][0]["errors"] == []++ assert AttributeValue.objects.filter(pk=old_value.pk).exists() is False+ new_value = AssignedVariantAttributeValue.objects.get(+ assignment__variant=variant, value__attribute=file_attribute+ ).value+ assert new_value.file_url == file_name+++def test_page_replace_deletes_previous_value(+ staff_api_client,+ page,+ page_file_attribute,+ permission_manage_pages,+):+ # given+ page.page_type.page_attributes.add(page_file_attribute)+ old_value = page_file_attribute.values.first()+ associate_attribute_values_to_instance(page, {page_file_attribute.pk: [old_value]})++ file_name = "new_file.jpg"+ variables = {+ "id": graphene.Node.to_global_id("Page", page.pk),+ "attributes": [+ {+ "id": graphene.Node.to_global_id("Attribute", page_file_attribute.pk),+ "file": build_file_url(file_name),+ }+ ],+ }++ # when+ response = staff_api_client.post_graphql(+ PAGE_UPDATE_MUTATION, variables, permissions=[permission_manage_pages]+ )++ # then+ content = get_graphql_content(response)+ assert content["data"]["pageUpdate"]["errors"] == []++ assert AttributeValue.objects.filter(pk=old_value.pk).exists() is False+ new_value = AssignedPageAttributeValue.objects.get(+ page=page, value__attribute=page_file_attribute+ ).value+ assert new_value.file_url == file_name+++def test_page_clear_deletes_previous_value(+ staff_api_client,+ page,+ page_file_attribute,+ permission_manage_pages,+):+ # given+ page.page_type.page_attributes.add(page_file_attribute)+ old_value = page_file_attribute.values.first()+ associate_attribute_values_to_instance(page, {page_file_attribute.pk: [old_value]})++ variables = {+ "id": graphene.Node.to_global_id("Page", page.pk),+ "attributes": [+ {+ "id": graphene.Node.to_global_id("Attribute", page_file_attribute.pk),+ "file": None,+ }+ ],+ }++ # when+ response = staff_api_client.post_graphql(+ PAGE_UPDATE_MUTATION, variables, permissions=[permission_manage_pages]+ )++ # then+ content = get_graphql_content(response)+ assert content["data"]["pageUpdate"]["errors"] == []++ assert AttributeValue.objects.filter(pk=old_value.pk).exists() is False+ assert (+ AssignedPageAttributeValue.objects.filter(+ page=page, value__attribute=page_file_attribute+ ).exists()+ is False+ )+++def test_customer_update_clear_deletes_previous_value(+ staff_api_client,+ customer_user,+ customer_type,+ permission_manage_users,+):+ # given+ file_attribute = Attribute.objects.create(+ slug="contract",+ name="Contract",+ type=AttributeType.CUSTOMER_TYPE,+ input_type=AttributeInputType.FILE,+ )+ old_value = AttributeValue.objects.create(+ attribute=file_attribute,+ name="contract.pdf",+ slug="contractpdf",+ file_url="contract.pdf",+ )+ customer_type.customer_attributes.add(file_attribute)+ customer_user.customer_type = customer_type+ customer_user.save(update_fields=["customer_type"])+ associate_attribute_values_to_instance(+ customer_user, {file_attribute.pk: [old_value]}+ )++ variables = {+ "id": graphene.Node.to_global_id("User", customer_user.pk),+ "attributes": [+ {+ "id": graphene.Node.to_global_id("Attribute", file_attribute.pk),+ "file": None,+ }+ ],+ }++ # when+ response = staff_api_client.post_graphql(+ CUSTOMER_UPDATE_MUTATION, variables, permissions=[permission_manage_users]+ )++ # then+ content = get_graphql_content(response)+ assert content["data"]["customerUpdate"]["errors"] == []++ assert AttributeValue.objects.filter(pk=old_value.pk).exists() is False+ assert customer_user.attributevalues.exists() is Falsediff --git a/saleor/graphql/attribute/utils/attribute_assignment.py b/saleor/graphql/attribute/utils/attribute_assignment.pyindex 8b2957a0c4..6201dd1d90 100644--- a/saleor/graphql/attribute/utils/attribute_assignment.py+++ b/saleor/graphql/attribute/utils/attribute_assignment.py@@ -3,12 +3,14 @@ from typing import TYPE_CHECKING, castimport graphenefrom django.core.exceptions import ValidationError+from django.db import transactionfrom django.db.models import Prefetch, Qfrom django.db.models.expressions import Exists, OuterReffrom graphql.error import GraphQLErrorfrom ....attribute import AttributeInputTypefrom ....attribute import models as attribute_models+from ....attribute.lock_objects import attribute_value_qs_select_for_updatefrom ....attribute.models import AttributeValuefrom ....attribute.utils import associate_attribute_values_to_instancefrom ....page import models as page_models@@ -22,6 +24,7 @@ from .shared import (T_INSTANCE,AttrValuesInput,get_assigned_attribute_values_map,+ get_assigned_attribute_values_qs,get_assignment_model_and_fk,)from .type_handlers import (@@ -47,6 +50,12 @@ T_PRE_SAVE_BULK = dict[AttributeValueBulkActionEnum, dict[attribute_models.Attribute, list]]+# Input types whose values are created per assigned instance and owned by it,+# so the instance's save owns their lifecycle and reclaims rows it detaches.+# REFERENCE and SINGLE_REFERENCE values have the same per-instance lifecycle+# and may be added here once their cleanup is desired.+INPUT_TYPES_WITH_INSTANCE_OWNED_VALUES = (AttributeInputType.FILE,)+class AttributeAssignmentMixin:"""Handles cleaning, validation, and saving of attribute data."""@@ -407,6 +416,15 @@ class AttributeAssignmentMixin:pre_save_bulk = cls.pre_save_values(instance, cleaned_input)attribute_and_values = cls._bulk_create_pre_save_values(pre_save_bulk)+ owned_value_attribute_pks = [+ attribute.pk+ for attribute in attribute_and_values+ if attribute.input_type in INPUT_TYPES_WITH_INSTANCE_OWNED_VALUES+ ]+ previous_owned_value_pks = cls._get_assigned_value_pks(+ instance, owned_value_attribute_pks+ )+attr_val_map = defaultdict(list)clean_assignment_pks = []for attribute, values in attribute_and_values.items():@@ -419,6 +437,10 @@ class AttributeAssignmentMixin:cls._clean_assignments(instance, clean_assignment_pks)+ cls._delete_orphaned_owned_values(+ instance, previous_owned_value_pks, owned_value_attribute_pks+ )+@classmethoddef _clean_assignments(cls, instance: T_INSTANCE, clean_assignment_pks: list[int]):"""Clean attribute assignments from the given instance."""@@ -452,6 +474,87 @@ class AttributeAssignmentMixin:variant_id=instance.id,).delete()+ @classmethod+ def _get_assigned_value_pks(+ cls, instance: T_INSTANCE, attribute_pks: list[int]+ ) -> list[int]:+ """Capture the pks of the values assigned to the instance.++ Uses the assignment queryset rather than+ `get_assigned_attribute_values_map`, which keeps a single value per+ attribute and would miss extra assigned rows legacy data may hold.+ """+ if not attribute_pks:+ return []+ return list(+ get_assigned_attribute_values_qs(instance, attribute_pks).values_list(+ "pk", flat=True+ )+ )++ @classmethod+ def _delete_orphaned_owned_values(+ cls,+ instance: T_INSTANCE,+ previous_value_pks: list[int],+ attribute_pks: list[int],+ ):+ """Delete instance-owned values this save detached from the instance.++ The file handler creates a new value row for every new URL instead+ of updating the assigned row in place, so a replace or clear leaves+ the previous row behind. Reclaimed are the rows that were assigned+ to the instance before this save and are assigned to nothing after+ it. `_exclude_values_assigned_to_any_entity` keeps the legacy rows+ that another entity still uses.+ """+ if not previous_value_pks:+ return++ candidates = attribute_models.AttributeValue.objects.filter(+ pk__in=previous_value_pks+ ).exclude(+ # The same-URL reuse path keeps the previously assigned row attached,+ # so a row still assigned to the instance must survive. Redundant with+ # the broad guard below today — kept so that guard stays droppable+ # without taking this correctness case down with it.+ pk__in=get_assigned_attribute_values_qs(instance, attribute_pks)+ )+ candidates = cls._exclude_values_assigned_to_any_entity(candidates)++ with transaction.atomic():+ locked_pks = (+ attribute_value_qs_select_for_update()+ .filter(pk__in=candidates)+ .values_list("pk", flat=True)+ )+ attribute_models.AttributeValue.objects.filter(pk__in=locked_pks).delete()++ @classmethod+ def _exclude_values_assigned_to_any_entity(+ cls, qs: "QuerySet[AttributeValue]"+ ) -> "QuerySet[AttributeValue]":+ """Exclude values still referenced by any attribute assignment.++ The instance's own assignments are already removed at this point, so+ a remaining reference means the row is shared with another entity.+ Current write paths cannot produce such a row, but the schema permits+ it and legacy rows may exist. The sibling cleanups on entity deletion+ (e.g. `ProductDelete.delete_assigned_attribute_values`) delete+ unconditionally, so this guard may be dropped if it proves not worth+ its cost.+ """+ for assignment_model in (+ attribute_models.AssignedProductAttributeValue,+ attribute_models.AssignedPageAttributeValue,+ attribute_models.AssignedUserAttributeValue,+ attribute_models.AssignedVariantAttributeValue,+ ):+ qs = qs.exclude(+ Exists(assignment_model.objects.filter(value_id=OuterRef("pk")))+ )+ return qs+@classmethoddef _bulk_create_pre_save_values(cls, pre_save_bulk):"""Execute bulk database operations based on prepared data."""diff --git a/saleor/graphql/attribute/utils/shared.py b/saleor/graphql/attribute/utils/shared.pyindex 572322881c..733f3f52f7 100644--- a/saleor/graphql/attribute/utils/shared.py+++ b/saleor/graphql/attribute/utils/shared.py@@ -110,7 +110,7 @@ def get_assignment_model_and_fk(instance: T_INSTANCE):)-def _get_assigned_attribute_values_qs(instance: T_INSTANCE, attribute_ids: list[int]):+def get_assigned_attribute_values_qs(instance: T_INSTANCE, attribute_ids: list[int]):"""Build a queryset of values currently assigned to the given instance."""if isinstance(instance, product_models.ProductVariant):# variant has old attribute structure so need to handle it differently@@ -143,7 +143,7 @@ def get_assigned_attribute_value_if_exists():"""Unified method to find an existing assigned value."""return (- _get_assigned_attribute_values_qs(instance, [attribute.pk])+ get_assigned_attribute_values_qs(instance, [attribute.pk]).filter(**{lookup_field: value}).first())@@ -154,7 +154,7 @@ def get_assigned_attribute_values_map() -> dict[int, attribute_models.AttributeValue]:"""Map attribute id to the value currently assigned to the instance."""values_map: dict[int, attribute_models.AttributeValue] = {}- for value in _get_assigned_attribute_values_qs(instance, attribute_ids):+ for value in get_assigned_attribute_values_qs(instance, attribute_ids):values_map.setdefault(value.attribute_id, value)return values_map