Skip to content

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

Fix products and variants with the same id overwriting each other's attribute values (#19510)

Marcin Wcisło8491ce69d0d6
diff --git a/saleor/graphql/attribute/tests/test_utils.py b/saleor/graphql/attribute/tests/test_utils.py
index ecba8d309a..7b75a263cf 100644
--- a/saleor/graphql/attribute/tests/test_utils.py
+++ b/saleor/graphql/attribute/tests/test_utils.py
@@ -2634,7 +2634,7 @@ def test_has_input_modified_attribute_values_no_changes_plain_text(
plain_text_attribute: [
{
"attribute": plain_text_attribute,
- "slug": f"{variant.id}_{plain_text_attribute.id}",
+ "slug": f"productvariant-{variant.id}_{plain_text_attribute.id}",
"defaults": {
"plain_text": text_value.plain_text,
"name": text_value.name,
@@ -2667,7 +2667,7 @@ def test_has_input_modified_attribute_values_with_changes_plain_text(
plain_text_attribute: [
{
"attribute": plain_text_attribute,
- "slug": f"{variant.id}_{plain_text_attribute.id}",
+ "slug": f"productvariant-{variant.id}_{plain_text_attribute.id}",
"defaults": {
"plain_text": different_text,
"name": different_text[:200],
@@ -2699,7 +2699,7 @@ def test_has_input_modified_attribute_values_no_changes_rich_text(
rich_text_attribute: [
{
"attribute": rich_text_attribute,
- "slug": f"{variant.id}_{rich_text_attribute.id}",
+ "slug": f"productvariant-{variant.id}_{rich_text_attribute.id}",
"defaults": {
"rich_text": rich_text_value.rich_text,
"name": rich_text_value.name,
@@ -2734,7 +2734,7 @@ def test_has_input_modified_attribute_values_with_changes_rich_text(
rich_text_attribute: [
{
"attribute": rich_text_attribute,
- "slug": f"{variant.id}_{rich_text_attribute.id}",
+ "slug": f"productvariant-{variant.id}_{rich_text_attribute.id}",
"defaults": {
"rich_text": different_rich_text,
"name": "New content"[:200],
@@ -2766,7 +2766,7 @@ def test_has_input_modified_attribute_values_no_changes_numeric(
numeric_attribute: [
{
"attribute": numeric_attribute,
- "slug": f"{variant.id}_{numeric_attribute.id}",
+ "slug": f"productvariant-{variant.id}_{numeric_attribute.id}",
"defaults": {
"name": str(numeric_value.numeric),
"numeric": numeric_value.numeric,
@@ -2799,7 +2799,7 @@ def test_has_input_modified_attribute_values_with_changes_numeric(
numeric_attribute: [
{
"attribute": numeric_attribute,
- "slug": f"{variant.id}_{numeric_attribute.id}",
+ "slug": f"productvariant-{variant.id}_{numeric_attribute.id}",
"defaults": {
"name": str(different_numeric),
"numeric": different_numeric,
@@ -2829,7 +2829,7 @@ def test_has_input_modified_attribute_values_no_changes_date(variant, date_attri
date_attribute: [
{
"attribute": date_attribute,
- "slug": f"{variant.id}_{date_attribute.id}",
+ "slug": f"productvariant-{variant.id}_{date_attribute.id}",
"defaults": {
"name": str(date_value.date_time.date()),
"date_time": date_value.date_time,
@@ -2863,7 +2863,7 @@ def test_has_input_modified_attribute_values_with_changes_date(variant, date_att
date_attribute: [
{
"attribute": date_attribute,
- "slug": f"{variant.id}_{date_attribute.id}",
+ "slug": f"productvariant-{variant.id}_{date_attribute.id}",
"defaults": {
"name": str(different_date),
"date_time": different_date_time,
@@ -2895,7 +2895,7 @@ def test_has_input_modified_attribute_values_no_changes_date_time(
date_time_attribute: [
{
"attribute": date_time_attribute,
- "slug": f"{variant.id}_{date_time_attribute.id}",
+ "slug": f"productvariant-{variant.id}_{date_time_attribute.id}",
"defaults": {
"name": str(date_time_value.date_time),
"date_time": date_time_value.date_time,
@@ -2928,7 +2928,7 @@ def test_has_input_modified_attribute_values_with_changes_date_time(
date_time_attribute: [
{
"attribute": date_time_attribute,
- "slug": f"{variant.id}_{date_time_attribute.id}",
+ "slug": f"productvariant-{variant.id}_{date_time_attribute.id}",
"defaults": {
"name": str(different_date_time),
"date_time": different_date_time,
@@ -2997,7 +2997,7 @@ def test_has_input_modified_attribute_values_mixed_bulk_actions(
plain_text_attribute: [
{
"attribute": plain_text_attribute,
- "slug": f"{variant.id}_{plain_text_attribute.id}",
+ "slug": f"productvariant-{variant.id}_{plain_text_attribute.id}",
"defaults": {
"plain_text": text_value.plain_text,
"name": text_value.name,
diff --git a/saleor/graphql/attribute/utils/attribute_assignment.py b/saleor/graphql/attribute/utils/attribute_assignment.py
index 0aa65de9f5..8fe052da16 100644
--- a/saleor/graphql/attribute/utils/attribute_assignment.py
+++ b/saleor/graphql/attribute/utils/attribute_assignment.py
@@ -22,6 +22,7 @@ from .shared import (
T_ERROR_DICT,
T_INSTANCE,
AttrValuesInput,
+ get_assigned_attribute_values_map,
get_assignment_model_and_fk,
)
from .type_handlers import (
@@ -311,7 +312,7 @@ class AttributeAssignmentMixin:
<Attribute>: [
{
"attribute": <Attribute>,
- "slug": "instance_id_attribute_id",
+ "slug": "<assigned value slug or model_name-instance_id_attribute_id>",
"defaults": {"name": "...", "plain_text": "..."}
}
],
@@ -362,8 +363,38 @@ class AttributeAssignmentMixin:
for action, value_data in prepared_values:
pre_save_bulk[action][attribute].append(value_data)
+ cls._use_assigned_value_slugs(instance, pre_save_bulk)
return pre_save_bulk
+ @classmethod
+ def _use_assigned_value_slugs(
+ cls, instance: T_INSTANCE, pre_save_bulk: T_PRE_SAVE_BULK
+ ):
+ """Update values assigned to the instance in place under their existing slug.
+
+ Update-or-create actions match values by slug, and the handlers
+ generate the entity-aware `{model name}-{instance pk}_{attribute pk}`
+ format. Values assigned before that format was introduced (or with
+ hand-crafted slugs) would not be matched and would be replaced with
+ new rows, losing their translations and external references — so for
+ attributes with a value already assigned to the instance, match that
+ value by its existing slug instead.
+ """
+ update_or_create = pre_save_bulk.get(
+ AttributeValueBulkActionEnum.UPDATE_OR_CREATE
+ )
+ if not update_or_create:
+ return
+ assigned_values = get_assigned_attribute_values_map(
+ instance, [attribute.pk for attribute in update_or_create]
+ )
+ for attribute, values in update_or_create.items():
+ assigned_value = assigned_values.get(attribute.pk)
+ if not assigned_value:
+ continue
+ for value_data in values:
+ value_data["slug"] = assigned_value.slug
+
@classmethod
def save(
cls,
diff --git a/saleor/graphql/attribute/utils/shared.py b/saleor/graphql/attribute/utils/shared.py
index 3b0ee84e52..0bd7943d3b 100644
--- a/saleor/graphql/attribute/utils/shared.py
+++ b/saleor/graphql/attribute/utils/shared.py
@@ -1,7 +1,7 @@
import datetime
from collections import defaultdict
from dataclasses import dataclass
-from typing import TYPE_CHECKING, NamedTuple, cast
+from typing import TYPE_CHECKING, NamedTuple
import orjson
from django.db.models import Model
@@ -101,46 +101,53 @@ def get_assignment_model_and_fk(instance: T_INSTANCE):
)
-def get_assigned_attribute_value_if_exists(
- instance: T_INSTANCE, attribute: "Attribute", lookup_field: str, value
-):
- """Unified method to find an existing assigned value."""
+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
- return get_variant_assigned_attribute_value_if_exists(
- instance, attribute, lookup_field, value
+ attribute_variant = Exists(
+ attribute_models.AttributeVariant.objects.filter(
+ pk=OuterRef("assignment_id"),
+ attribute_id__in=attribute_ids,
+ )
)
+ assigned_variant = Exists(
+ attribute_models.AssignedVariantAttribute.objects.filter(
+ attribute_variant
+ ).filter(
+ variant_id=instance.pk,
+ values=OuterRef("pk"),
+ )
+ )
+ return attribute_models.AttributeValue.objects.filter(assigned_variant)
assignment_model, instance_fk = get_assignment_model_and_fk(instance)
assigned_values = assignment_model.objects.filter(**{instance_fk: instance.pk})
return attribute_models.AttributeValue.objects.filter(
Exists(assigned_values.filter(value_id=OuterRef("id"))),
- attribute_id=attribute.pk,
- **{lookup_field: value},
- ).first()
+ attribute_id__in=attribute_ids,
+ )
-def get_variant_assigned_attribute_value_if_exists(
- instance: T_INSTANCE, attribute: "Attribute", lookup_field: str, value: str
+def get_assigned_attribute_value_if_exists(
+ instance: T_INSTANCE, attribute: "Attribute", lookup_field: str, value
):
- variant = cast(product_models.ProductVariant, instance)
- attribute_variant = Exists(
- attribute_models.AttributeVariant.objects.filter(
- pk=OuterRef("assignment_id"),
- attribute_id=attribute.pk,
- )
- )
- assigned_variant = Exists(
- attribute_models.AssignedVariantAttribute.objects.filter(
- attribute_variant
- ).filter(
- variant_id=variant.pk,
- values=OuterRef("pk"),
- )
+ """Unified method to find an existing assigned value."""
+ return (
+ _get_assigned_attribute_values_qs(instance, [attribute.pk])
+ .filter(**{lookup_field: value})
+ .first()
)
- return attribute_models.AttributeValue.objects.filter(
- assigned_variant, **{lookup_field: value}
- ).first()
+
+
+def get_assigned_attribute_values_map(
+ instance: T_INSTANCE, attribute_ids: list[int]
+) -> 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):
+ values_map.setdefault(value.attribute_id, value)
+ return values_map
def has_input_modified_attribute_values(
diff --git a/saleor/graphql/attribute/utils/type_handlers.py b/saleor/graphql/attribute/utils/type_handlers.py
index 380899073f..d5e01cc86d 100644
--- a/saleor/graphql/attribute/utils/type_handlers.py
+++ b/saleor/graphql/attribute/utils/type_handlers.py
@@ -116,7 +116,21 @@ class AttributeTypeHandler(abc.ABC):
instance: T_INSTANCE,
value_defaults: dict,
):
- slug = slugify(unidecode(f"{instance.id}_{self.attribute.id}"))
+ """Prepare an update-or-create action for a value owned by the instance.
+
+ The slug must encode the entity type: products, variants and pages use
+ independent pk sequences, so the bare `{pk}_{attribute pk}` slug used
+ historically made a product and a variant with the same pk share (and
+ overwrite) a single value row.
+
+ The slug is a fallback for matching new values only — a value already
+ assigned to the instance is matched by the assignment and updated in
+ place under its existing slug; see
+ `AttributeAssignmentMixin._use_assigned_value_slugs`.
+ """
+ slug = slugify(
+ unidecode(f"{instance._meta.model_name}-{instance.pk}_{self.attribute.pk}")
+ )
value = {
"attribute": self.attribute,
"slug": slug,
diff --git a/saleor/graphql/page/tests/mutations/test_page_create.py b/saleor/graphql/page/tests/mutations/test_page_create.py
index 037a0b92d2..9dfdee1be2 100644
--- a/saleor/graphql/page/tests/mutations/test_page_create.py
+++ b/saleor/graphql/page/tests/mutations/test_page_create.py
@@ -1050,7 +1050,7 @@ def test_create_page_with_date_attribute(
"dateTime": None,
"date": str(date_value),
"name": str(date_value),
- "slug": f"{new_page_pk}_{date_attribute.id}",
+ "slug": f"page-{new_page_pk}_{date_attribute.id}",
}
],
}
@@ -1116,7 +1116,7 @@ def test_create_page_with_date_time_attribute(
"dateTime": date_time_value.isoformat(),
"date": None,
"name": str(date_time_value),
- "slug": f"{new_page_pk}_{date_time_attribute.id}",
+ "slug": f"page-{new_page_pk}_{date_time_attribute.id}",
}
],
}
@@ -1183,7 +1183,7 @@ def test_create_page_with_plain_text_attribute(
"date": None,
"name": text,
"plainText": text,
- "slug": f"{new_page_pk}_{plain_text_attribute_page_type.id}",
+ "slug": f"page-{new_page_pk}_{plain_text_attribute_page_type.id}",
}
],
}
@@ -2023,7 +2023,7 @@ def test_page_create_mutation_with_numeric_attribue(
assert len(attribute["values"]) == 1
assert (
attribute["values"][0]["slug"]
- == f"{Page.objects.get().id}_{numeric_attribute.id}"
+ == f"page-{Page.objects.get().id}_{numeric_attribute.id}"
)
assert attribute["values"][0]["name"] == numeric_name
diff --git a/saleor/graphql/page/tests/mutations/test_page_update.py b/saleor/graphql/page/tests/mutations/test_page_update.py
index a8c16d9d54..648135d8ae 100644
--- a/saleor/graphql/page/tests/mutations/test_page_update.py
+++ b/saleor/graphql/page/tests/mutations/test_page_update.py
@@ -733,7 +733,7 @@ def test_update_page_with_plain_text_attribute_new_value(
"attribute": {"slug": plain_text_attribute_page_type.slug},
"values": [
{
- "slug": f"{page.pk}_{plain_text_attribute_page_type.pk}",
+ "slug": f"page-{page.pk}_{plain_text_attribute_page_type.pk}",
"name": text,
"file": None,
"reference": None,
@@ -910,7 +910,7 @@ def test_update_page_with_plain_text_attribute_existing_value(
"Attribute", plain_text_attribute_page_type.pk
)
attribute_value = plain_text_attribute_page_type.values.first()
- attribute_value.slug = f"{page.pk}_{plain_text_attribute_page_type.pk}"
+ attribute_value.slug = f"page-{page.pk}_{plain_text_attribute_page_type.pk}"
attribute_value.save(update_fields=["slug"])
text = attribute_value.plain_text
@@ -977,7 +977,7 @@ def test_update_page_with_required_plain_text_attribute_empty_value(
"Attribute", plain_text_attribute_page_type.pk
)
attribute_value = plain_text_attribute_page_type.values.first()
- attribute_value.slug = f"{page.pk}_{plain_text_attribute_page_type.pk}"
+ attribute_value.slug = f"page-{page.pk}_{plain_text_attribute_page_type.pk}"
attribute_value.save(update_fields=["slug"])
plain_text_attribute_page_type.value_required = True
@@ -2007,7 +2007,9 @@ def test_update_page_with_numeric_attribute(
assert len(attributes) == 1
assert attributes[0]["attribute"]["slug"] == numeric_attribute.slug
assert len(attributes[0]["values"]) == 1
- assert attributes[0]["values"][0]["slug"] == f"{page.pk}_{numeric_attribute.pk}"
+ assert (
+ attributes[0]["values"][0]["slug"] == f"page-{page.pk}_{numeric_attribute.pk}"
+ )
assert attributes[0]["values"][0]["name"] == numeric_name
assigned_attributes = data["page"]["assignedAttributes"]
diff --git a/saleor/graphql/product/tests/mutations/test_product_create.py b/saleor/graphql/product/tests/mutations/test_product_create.py
index 4e4b4b50b9..316b952c90 100644
--- a/saleor/graphql/product/tests/mutations/test_product_create.py
+++ b/saleor/graphql/product/tests/mutations/test_product_create.py
@@ -679,7 +679,7 @@ def test_create_product_with_rich_text_attribute(
"attribute": {"slug": "text"},
"values": [
{
- "slug": f"{product_id}_{rich_text_attribute.id}",
+ "slug": f"product-{product_id}_{rich_text_attribute.id}",
"name": (
"test producttest producttest producttest producttest product"
),
@@ -819,7 +819,7 @@ def test_create_product_with_plain_text_attribute(
"attribute": {"slug": plain_text_attribute.slug},
"values": [
{
- "slug": f"{product_id}_{plain_text_attribute.id}",
+ "slug": f"product-{product_id}_{plain_text_attribute.id}",
"name": text_value,
"reference": None,
"richText": None,
@@ -949,7 +949,7 @@ def test_create_product_with_date_time_attribute(
"attribute": {"slug": "release-date-time"},
"values": [
{
- "slug": f"{product_id}_{date_time_attribute.id}",
+ "slug": f"product-{product_id}_{date_time_attribute.id}",
"name": str(value),
"reference": None,
"richText": None,
@@ -1018,7 +1018,7 @@ def test_create_product_with_date_attribute(
"attribute": {"slug": "release-date"},
"values": [
{
- "slug": f"{product_id}_{date_attribute.id}",
+ "slug": f"product-{product_id}_{date_attribute.id}",
"name": str(value),
"reference": None,
"richText": None,
@@ -3249,7 +3249,7 @@ def test_create_product_with_numeric_attribute_new_attribute_value(
values = data["product"]["attributes"][0]["values"]
assert len(values) == 1
assert values[0]["name"] == expected_name
- assert values[0]["slug"] == f"{product_pk}_{numeric_attribute.id}"
+ assert values[0]["slug"] == f"product-{product_pk}_{numeric_attribute.id}"
assigned_attributes = data["product"]["assignedAttributes"]
expected_assigned_attribute = {
@@ -3312,7 +3312,7 @@ def test_create_product_with_numeric_attribute_existing_value(
values = data["product"]["attributes"][0]["values"]
assert len(values) == 1
assert values[0]["name"] == existing_value.name
- assert values[0]["slug"] == f"{product_pk}_{numeric_attribute.id}"
+ assert values[0]["slug"] == f"product-{product_pk}_{numeric_attribute.id}"
numeric_attribute.refresh_from_db()
assert numeric_attribute.values.count() == values_count + 1
diff --git a/saleor/graphql/product/tests/mutations/test_product_update.py b/saleor/graphql/product/tests/mutations/test_product_update.py
index 605d7219d8..b7c75bd667 100644
--- a/saleor/graphql/product/tests/mutations/test_product_update.py
+++ b/saleor/graphql/product/tests/mutations/test_product_update.py
@@ -799,7 +799,7 @@ def test_update_product_with_numeric_attribute_value(
"id": ANY,
"name": new_value,
"slug": slugify(
- f"{product.id}_{numeric_attribute.id}", allow_unicode=True
+ f"product-{product.id}_{numeric_attribute.id}", allow_unicode=True
),
"reference": None,
"file": None,
@@ -841,7 +841,9 @@ def test_update_product_with_numeric_attribute_value_new_value_is_not_created(
attribute_id = graphene.Node.to_global_id("Attribute", numeric_attribute.pk)
product_type.product_attributes.add(numeric_attribute)
- slug_value = slugify(f"{product.id}_{numeric_attribute.id}", allow_unicode=True)
+ slug_value = slugify(
+ f"product-{product.id}_{numeric_attribute.id}", allow_unicode=True
+ )
value = AttributeValue.objects.create(
attribute=numeric_attribute, slug=slug_value, name="20.0", numeric=20.0
)
@@ -1155,7 +1157,7 @@ def test_update_product_with_plain_text_attribute_value(
"values": [
{
"id": ANY,
- "slug": f"{product.id}_{plain_text_attribute.id}",
+ "slug": f"product-{product.id}_{plain_text_attribute.id}",
"name": text,
"reference": None,
"file": None,
@@ -1220,7 +1222,7 @@ def test_update_product_with_plain_text_attribute_value_required(
"values": [
{
"id": ANY,
- "slug": f"{product.id}_{plain_text_attribute.id}",
+ "slug": f"product-{product.id}_{plain_text_attribute.id}",
"name": text,
"reference": None,
"file": None,
@@ -2897,7 +2899,7 @@ def test_update_product_with_numeric_attribute_value_by_numeric_field(
"id": ANY,
"name": new_value,
"slug": slugify(
- f"{product.id}_{numeric_attribute.id}", allow_unicode=True
+ f"product-{product.id}_{numeric_attribute.id}", allow_unicode=True
),
"reference": None,
"file": None,
@@ -2936,7 +2938,9 @@ def test_update_product_with_numeric_attribute_by_numeric_field_null_value(
attribute_id = graphene.Node.to_global_id("Attribute", numeric_attribute.pk)
product_type.product_attributes.add(numeric_attribute)
- slug_value = slugify(f"{product.id}_{numeric_attribute.id}", allow_unicode=True)
+ slug_value = slugify(
+ f"product-{product.id}_{numeric_attribute.id}", allow_unicode=True
+ )
value = AttributeValue.objects.create(
attribute=numeric_attribute, slug=slug_value, name="20.0", numeric=20.0
)
@@ -2980,7 +2984,9 @@ def test_update_product_with_numeric_attribute_by_numeric_field_new_value_not_cr
attribute_id = graphene.Node.to_global_id("Attribute", numeric_attribute.pk)
product_type.product_attributes.add(numeric_attribute)
- slug_value = slugify(f"{product.id}_{numeric_attribute.id}", allow_unicode=True)
+ slug_value = slugify(
+ f"product-{product.id}_{numeric_attribute.id}", allow_unicode=True
+ )
value = AttributeValue.objects.create(
attribute=numeric_attribute, slug=slug_value, name="20.0", numeric=20.0
)
diff --git a/saleor/graphql/product/tests/mutations/test_product_variant_create.py b/saleor/graphql/product/tests/mutations/test_product_variant_create.py
index a4eb609329..7f1881251e 100644
--- a/saleor/graphql/product/tests/mutations/test_product_variant_create.py
+++ b/saleor/graphql/product/tests/mutations/test_product_variant_create.py
@@ -1865,7 +1865,7 @@ def test_create_variant_with_numeric_attribute(
assert data["attributes"][0]["attribute"]["slug"] == variant_slug
assert (
data["attributes"][0]["values"][0]["slug"]
- == f"{variant_pk}_{numeric_attribute.pk}"
+ == f"productvariant-{variant_pk}_{numeric_attribute.pk}"
)
assigned_attributes = data["assignedAttributes"]
@@ -2439,7 +2439,7 @@ def test_create_variant_with_date_attribute(
"dateTime": None,
"date": str(date_value),
"name": str(date_value),
- "slug": f"{variant.id}_{date_attribute.id}",
+ "slug": f"productvariant-{variant.id}_{date_attribute.id}",
}
],
}
@@ -2509,7 +2509,7 @@ def test_create_variant_with_date_time_attribute(
"dateTime": date_time_value.isoformat(),
"date": None,
"name": str(date_time_value),
- "slug": f"{variant.id}_{date_time_attribute.id}",
+ "slug": f"productvariant-{variant.id}_{date_time_attribute.id}",
}
],
}
diff --git a/saleor/graphql/product/tests/mutations/test_product_variant_update.py b/saleor/graphql/product/tests/mutations/test_product_variant_update.py
index 65cb398101..c9437f374c 100644
--- a/saleor/graphql/product/tests/mutations/test_product_variant_update.py
+++ b/saleor/graphql/product/tests/mutations/test_product_variant_update.py
@@ -13,6 +13,7 @@ from .....attribute import AttributeInputType
from .....attribute.models import AttributeValue
from .....attribute.utils import associate_attribute_values_to_instance
from .....product.error_codes import ProductErrorCode
+from .....product.models import Product, ProductVariant
from ....core.utils import snake_to_camel_case
from ....tests.utils import get_graphql_content
from ...mutations.product_variant.product_variant_create import ProductVariantInput
@@ -1377,7 +1378,9 @@ def test_update_variant_with_rich_text_attribute(
{"id": attr_id, "richText": json.dumps(rich_text, sort_keys=True)},
],
}
- rich_text_attribute_value.slug = f"{variant.id}_{rich_text_attribute.id}"
+ rich_text_attribute_value.slug = (
+ f"productvariant-{variant.id}_{rich_text_attribute.id}"
+ )
rich_text_attribute_value.save()
values_count = rich_text_attribute.values.count()
associate_attribute_values_to_instance(
@@ -1435,7 +1438,9 @@ def test_update_variant_with_plain_text_attribute(
{"id": attr_id, "plainText": text},
],
}
- plain_text_attribute_value.slug = f"{variant.id}_{plain_text_attribute.id}"
+ plain_text_attribute_value.slug = (
+ f"productvariant-{variant.id}_{plain_text_attribute.id}"
+ )
plain_text_attribute_value.save()
values_count = plain_text_attribute.values.count()
associate_attribute_values_to_instance(
@@ -1494,7 +1499,9 @@ def test_update_variant_with_plain_text_attribute_value_required(
{"id": attr_id, "plainText": text},
],
}
- plain_text_attribute_value.slug = f"{variant.id}_{plain_text_attribute.id}"
+ plain_text_attribute_value.slug = (
+ f"productvariant-{variant.id}_{plain_text_attribute.id}"
+ )
plain_text_attribute_value.save()
plain_text_attribute.value_required = True
@@ -1549,7 +1556,9 @@ def test_update_variant_with_required_plain_text_attribute_no_value(
attr_id = graphene.Node.to_global_id("Attribute", plain_text_attribute.id)
plain_text_attribute_value = plain_text_attribute.values.first()
- plain_text_attribute_value.slug = f"{variant.id}_{plain_text_attribute.id}"
+ plain_text_attribute_value.slug = (
+ f"productvariant-{variant.id}_{plain_text_attribute.id}"
+ )
plain_text_attribute_value.save()
associate_attribute_values_to_instance(
@@ -1632,7 +1641,7 @@ def test_update_variant_with_date_attribute(
"dateTime": None,
"date": str(date_value),
"name": str(date_value),
- "slug": f"{variant.id}_{date_attribute.id}",
+ "slug": f"productvariant-{variant.id}_{date_attribute.id}",
}
],
}
@@ -1702,7 +1711,7 @@ def test_update_variant_with_date_time_attribute(
"dateTime": date_time_value.isoformat(),
"date": None,
"name": str(date_time_value),
- "slug": f"{variant.id}_{date_time_attribute.id}",
+ "slug": f"productvariant-{variant.id}_{date_time_attribute.id}",
}
],
}
@@ -1746,7 +1755,7 @@ def test_update_variant_removes_numeric_attribute_value(
{"id": attr_id, "values": []},
],
}
- attribute_value.slug = f"{variant.id}_{numeric_attribute.id}"
+ attribute_value.slug = f"productvariant-{variant.id}_{numeric_attribute.id}"
attribute_value.save()
values_count = numeric_attribute.values.count()
associate_attribute_values_to_instance(
@@ -1836,6 +1845,348 @@ def test_update_variant_adds_numeric_attribute(
product_variant_updated.assert_called_once_with(product.variants.last())
+def test_update_variant_numeric_attribute_does_not_change_product_with_same_pk(
+ staff_api_client,
+ permission_manage_products,
+ numeric_attribute,
+ product_type_generator,
+ category,
+):
+ """Value slug `{instance.id}_{attribute.id}` must not collide across entity types.
+
+ A product and a variant sharing the same numeric pk must not resolve to the
+ same AttributeValue row when the same attribute is used as a product
+ attribute on one product type and as a variant attribute on another.
+ """
+ # given
+ product_type_with_product_attr = product_type_generator(
+ name="Type with product attribute",
+ slug="type-with-product-attribute",
+ has_variants=False,
+ product_attributes=[numeric_attribute],
+ variant_attributes=[],
+ )
+ product_type_with_variant_attr = product_type_generator(
+ name="Type with variant attribute",
+ slug="type-with-variant-attribute",
+ has_variants=True,
+ product_attributes=[],
+ variant_attributes=[numeric_attribute],
+ )
+
+ product = Product.objects.create(
+ name="Product with numeric attribute",
+ slug="product-with-numeric-attribute",
+ product_type=product_type_with_product_attr,
+ category=category,
+ )
+ other_product = Product.objects.create(
+ name="Unrelated product",
+ slug="unrelated-product",
+ product_type=product_type_with_variant_attr,
+ category=category,
+ )
+ # force the pk collision between the product and the variant
+ variant = ProductVariant.objects.create(
+ pk=product.pk, product=other_product, sku="colliding-variant"
+ )
+
+ product_numeric_name = "221"
+ product_numeric_value = 221.0
+ # the value uses the legacy slug format that did not encode the entity type
+ product_value = AttributeValue.objects.create(
+ attribute=numeric_attribute,
+ slug=slugify(f"{product.pk}_{numeric_attribute.pk}", allow_unicode=True),
+ name=product_numeric_name,
+ numeric=product_numeric_value,
+ )
+ associate_attribute_values_to_instance(
+ product, {numeric_attribute.pk: [product_value]}
+ )
+
+ variant_numeric_name = "999"
+ variant_numeric_value = 999.0
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
+ attr_id = graphene.Node.to_global_id("Attribute", numeric_attribute.pk)
+ variables = {
+ "id": variant_id,
+ "attributes": [
+ {"id": attr_id, "numeric": variant_numeric_name},
+ ],
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_UPDATE_VARIANT_ATTRIBUTES,
+ variables,
+ permissions=[permission_manage_products],
+ )
+
+ # then
+ content = get_graphql_content(response)["data"]["productVariantUpdate"]
+ assert len(content["errors"]) == 0
+
+ assigned_attributes = content["productVariant"]["assignedAttributes"]
+ expected_assigned_attribute = {
+ "attribute": {"slug": numeric_attribute.slug},
+ "value": variant_numeric_value,
+ }
+ assert expected_assigned_attribute in assigned_attributes
+
+ # the variant got its own value row instead of hijacking the product's one
+ variant_value = variant.attributes.get().values.get()
+ assert variant_value.pk != product_value.pk
+ assert variant_value.name == variant_numeric_name
+ assert variant_value.numeric == variant_numeric_value
+
+ # the product's value is intact and still linked only to the product
+ product_value.refresh_from_db()
+ assert product_value.name == product_numeric_name
+ assert product_value.numeric == product_numeric_value
+ assert product_value.variantvalueassignment.exists() is False
+ assert product.attributevalues.get().value_id == product_value.pk
+
+
+def test_update_variant_numeric_attribute_keeps_updating_value_shared_with_product(
+ staff_api_client,
+ permission_manage_products,
+ numeric_attribute,
+ product_type_generator,
+ category,
+):
+ """Document the known limitation for values corrupted before the slug fix.
+
+ A value row that is already assigned to both a product and a variant (the
+ result of the historic `{instance.id}_{attribute.id}` slug collision) is
+ not healed automatically: updating the variant still updates the shared
+ row in place, changing the product's displayed value as well. Such rows
+ have to be split manually — see the instructions in the pull request that
+ introduced the entity-aware slug format.
+ """
+ # given
+ product_type_with_product_attr = product_type_generator(
+ name="Type with product attribute",
+ slug="type-with-product-attribute",
+ has_variants=False,
+ product_attributes=[numeric_attribute],
+ variant_attributes=[],
+ )
+ product_type_with_variant_attr = product_type_generator(
+ name="Type with variant attribute",
+ slug="type-with-variant-attribute",
+ has_variants=True,
+ product_attributes=[],
+ variant_attributes=[numeric_attribute],
+ )
+
+ product = Product.objects.create(
+ name="Product with numeric attribute",
+ slug="product-with-numeric-attribute",
+ product_type=product_type_with_product_attr,
+ category=category,
+ )
+ other_product = Product.objects.create(
+ name="Unrelated product",
+ slug="unrelated-product",
+ product_type=product_type_with_variant_attr,
+ category=category,
+ )
+ # force the pk collision between the product and the variant
+ variant = ProductVariant.objects.create(
+ pk=product.pk, product=other_product, sku="colliding-variant"
+ )
+
+ # the value was corrupted into cross-entity sharing before the slug fix:
+ # a single legacy-slug row assigned to both the product and the variant
+ shared_value = AttributeValue.objects.create(
+ attribute=numeric_attribute,
+ slug=slugify(f"{product.pk}_{numeric_attribute.pk}", allow_unicode=True),
+ name="221",
+ numeric=221.0,
+ )
+ associate_attribute_values_to_instance(
+ product, {numeric_attribute.pk: [shared_value]}
+ )
+ associate_attribute_values_to_instance(
+ variant, {numeric_attribute.pk: [shared_value]}
+ )
+ values_count = numeric_attribute.values.count()
+
+ variant_numeric_name = "999"
+ variant_numeric_value = 999.0
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
+ attr_id = graphene.Node.to_global_id("Attribute", numeric_attribute.pk)
+ variables = {
+ "id": variant_id,
+ "attributes": [
+ {"id": attr_id, "numeric": variant_numeric_name},
+ ],
+ }
+
+ # when
+ response = staff_api_client.post_graphql(
+ QUERY_UPDATE_VARIANT_ATTRIBUTES,
+ variables,
+ permissions=[permission_manage_products],
+ )
+
+ # then
+ content = get_graphql_content(response)["data"]["productVariantUpdate"]
+ assert len(content["errors"]) == 0
+
+ # the shared row is updated in place — no new row is created
+ shared_value.refresh_from_db()
+ assert shared_value.name == variant_numeric_name
+ assert shared_value.numeric == variant_numeric_value
+ assert numeric_attribute.values.count() == values_count
+ assert variant.attributes.get().values.get() == shared_value
+
+ # the product still shares the row, so its displayed value changed too
+ assert product.attributevalues.get().value_id == shared_value.pk
+
+
+def test_deleting_shared_value_and_re_adding_separates_product_and_variant(
+ staff_api_client,
+ permission_manage_products,
+ permission_manage_product_types_and_attributes,
+ numeric_attribute,
+ product_type_generator,
+ category,
+):
+ """Verify the manual remediation flow for values corrupted before the slug fix.
+
+ Deleting the shared value row unlinks both entities at once; re-entering
+ the values afterwards gives the product and the variant separate rows that
+ can no longer affect each other.
+ """
+ # given
+ product_type_with_product_attr = product_type_generator(
+ name="Type with product attribute",
+ slug="type-with-product-attribute",
+ has_variants=False,
+ product_attributes=[numeric_attribute],
+ variant_attributes=[],
+ )
+ product_type_with_variant_attr = product_type_generator(
+ name="Type with variant attribute",
+ slug="type-with-variant-attribute",
+ has_variants=True,
+ product_attributes=[],
+ variant_attributes=[numeric_attribute],
+ )
+
+ product = Product.objects.create(
+ name="Product with numeric attribute",
+ slug="product-with-numeric-attribute",
+ product_type=product_type_with_product_attr,
+ category=category,
+ )
+ other_product = Product.objects.create(
+ name="Unrelated product",
+ slug="unrelated-product",
+ product_type=product_type_with_variant_attr,
+ category=category,
+ )
+ # force the pk collision between the product and the variant
+ variant = ProductVariant.objects.create(
+ pk=product.pk, product=other_product, sku="colliding-variant"
+ )
+
+ # the value was corrupted into cross-entity sharing before the slug fix
+ shared_value = AttributeValue.objects.create(
+ attribute=numeric_attribute,
+ slug=slugify(f"{product.pk}_{numeric_attribute.pk}", allow_unicode=True),
+ name="999",
+ numeric=999.0,
+ )
+ associate_attribute_values_to_instance(
+ product, {numeric_attribute.pk: [shared_value]}
+ )
+ associate_attribute_values_to_instance(
+ variant, {numeric_attribute.pk: [shared_value]}
+ )
+
+ attr_id = graphene.Node.to_global_id("Attribute", numeric_attribute.pk)
+ product_id = graphene.Node.to_global_id("Product", product.pk)
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
+ product_numeric_name = "221"
+ product_numeric_value = 221.0
+ variant_numeric_name = "999"
+ variant_numeric_value = 999.0
+
+ # when
+ # step 1: delete the shared value, unlinking both entities at once
+ delete_response = staff_api_client.post_graphql(
+ """
+ mutation AttributeValueDelete($id: ID!) {
+ attributeValueDelete(id: $id) {
+ errors {
+ field
+ message
+ }
+ }
+ }
+ """,
+ {"id": graphene.Node.to_global_id("AttributeValue", shared_value.pk)},
+ permissions=[permission_manage_product_types_and_attributes],
+ )
+
+ # step 2: re-enter the value on the product
+ product_response = staff_api_client.post_graphql(
+ """
+ mutation ProductUpdate($id: ID!, $attributes: [AttributeValueInput!]) {
+ productUpdate(id: $id, input: {attributes: $attributes}) {
+ errors {
+ field
+ message
+ }
+ }
+ }
+ """,
+ {
+ "id": product_id,
+ "attributes": [{"id": attr_id, "numeric": product_numeric_name}],
+ },
+ permissions=[permission_manage_products],
+ )
+
+ # step 3: re-enter the value on the variant
+ variant_response = staff_api_client.post_graphql(
+ QUERY_UPDATE_VARIANT_ATTRIBUTES,
+ {
+ "id": variant_id,
+ "attributes": [{"id": attr_id, "numeric": variant_numeric_name}],
+ },
+ )
+
+ # then
+ delete_content = get_graphql_content(delete_response)["data"]
+ product_content = get_graphql_content(product_response)["data"]
+ variant_content = get_graphql_content(variant_response)["data"]
+ assert len(delete_content["attributeValueDelete"]["errors"]) == 0
+ assert len(product_content["productUpdate"]["errors"]) == 0
+ assert len(variant_content["productVariantUpdate"]["errors"]) == 0
+
+ assert AttributeValue.objects.filter(pk=shared_value.pk).exists() is False
+
+ # each entity got its own value row
+ product_value = numeric_attribute.values.get(
+ slug=f"product-{product.pk}_{numeric_attribute.pk}"
+ )
+ variant_value = numeric_attribute.values.get(
+ slug=f"productvariant-{variant.pk}_{numeric_attribute.pk}"
+ )
+ assert product_value.pk != variant_value.pk
+ assert product_value.name == product_numeric_name
+ assert product_value.numeric == product_numeric_value
+ assert variant_value.name == variant_numeric_name
+ assert variant_value.numeric == variant_numeric_value
+ assert product.attributevalues.get().value_id == product_value.pk
+ assert variant.attributes.get().values.get() == variant_value
+ assert product_value.variantvalueassignment.exists() is False
+ assert variant_value.productvalueassignment.exists() is False
+
+
def test_update_product_variant_with_new_attribute(
staff_api_client,
product_with_variant_with_two_attributes,