Skip to content

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

Fix resolving attribute values by slug

Marcin Gębala3d1599e05ea4
diff --git a/saleor/graphql/product/utils.py b/saleor/graphql/product/utils.py
index 16f0b04965..867d8e2d29 100644
--- a/saleor/graphql/product/utils.py
+++ b/saleor/graphql/product/utils.py
@@ -1,6 +1,6 @@
from django.utils.text import slugify
-from ...product.models import Attribute, AttributeValue
+from ...product.models import Attribute
def attributes_to_hstore(attribute_value_input, attributes_queryset):
@@ -13,7 +13,11 @@ def attributes_to_hstore(attribute_value_input, attributes_queryset):
attributes_map = {attr.slug: attr.id for attr in attributes_queryset}
attributes_hstore = {}
- values_map = dict(AttributeValue.objects.values_list("slug", "id"))
+
+ values_map = {}
+ for attr in attributes_queryset:
+ for value in attr.values.all():
+ values_map[value.slug] = value.id
for attribute in attribute_value_input:
attr_slug = attribute.get("slug")
diff --git a/tests/api/test_attributes.py b/tests/api/test_attributes.py
index 5e04e31fb2..9a1cbadb8f 100644
--- a/tests/api/test_attributes.py
+++ b/tests/api/test_attributes.py
@@ -34,6 +34,24 @@ def test_attributes_to_hstore(product, color_attribute):
attributes_to_hstore(input_data, attrs_qs)
+def test_attributes_to_hstore_duplicated_slug(product, color_attribute, size_attribute):
+ # It's possible to have a value with the same slug but for a different attribute.
+ # Ensure that `attributes_to_hstore` works in that case.
+
+ color_value = color_attribute.values.first()
+
+ # Create a fake duplicated value.
+ AttributeValue.objects.create(
+ slug=color_value.slug, name="Duplicated value", attribute=size_attribute
+ )
+
+ input_data = [{"slug": color_attribute.slug, "value": color_value.slug}]
+ attrs_qs = product.product_type.product_attributes.all()
+ ids = attributes_to_hstore(input_data, attrs_qs)
+ assert str(color_attribute.pk) in ids
+ assert ids[str(color_attribute.pk)] == str(color_value.pk)
+
+
def test_attributes_query(user_api_client, product):
attributes = Attribute.objects.prefetch_related("values")
query = """