Skip to content

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

Deprecate the slug field for value input in attributes, ID instead

NyanKiyoshi3d674b87ac68
diff --git a/CHANGELOG.md b/CHANGELOG.md
index aad7a3e62f..c3c4e1d9b4 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -18,6 +18,7 @@ All notable, unreleased changes to this project will be documented in this file.
- Added flags to attributes: whether they are filterable or not in dashboard and/or storefront. - #4341 by @NyanKiyoshi.
- Attributes can now be flagged as required. - #4340 by @NyanKiyoshi.
- Added a search position field for the storefront navigation to the attributes. - #4343 by @NyanKiyoshi
+- Deprecate the slug field for value input in attributes, and pass by ID instead. - #4348 by @NyanKiyoshi
## [Unreleased]
diff --git a/saleor/graphql/product/descriptions.py b/saleor/graphql/product/descriptions.py
index 52b04b032f..109ecceb3b 100644
--- a/saleor/graphql/product/descriptions.py
+++ b/saleor/graphql/product/descriptions.py
@@ -16,6 +16,7 @@ class AttributeDescriptions:
class AttributeValueDescriptions:
+ ID = "The ID of a value displayed in the interface."
NAME = "Name of a value displayed in the interface."
SLUG = "Internal representation of a value (unique per attribute)."
TYPE = """Type of value (used only when `value` field is set)."""
diff --git a/saleor/graphql/product/mutations/products.py b/saleor/graphql/product/mutations/products.py
index e81ecc97d4..890ee00404 100644
--- a/saleor/graphql/product/mutations/products.py
+++ b/saleor/graphql/product/mutations/products.py
@@ -1,4 +1,4 @@
-from typing import List, Tuple
+from typing import Dict, List, Tuple
import graphene
from django.core.exceptions import ValidationError
@@ -29,6 +29,7 @@ from ...core.utils import (
from_global_id_strict_type,
validate_image_file,
)
+from ...product.types import AttributeValue
from ..types import (
Category,
Collection,
@@ -393,6 +394,11 @@ class CategoryClearPrivateMeta(ClearMetaBaseMutation):
class AttributeValueInput(InputObjectType):
+ id = graphene.ID(description="ID of an attribute")
+ name = graphene.String(
+ description="Slug of an attribute",
+ deprecation_reason="name is deprecated, use id instead",
+ )
slug = graphene.String(required=True, description="Slug of an attribute.")
values = graphene.List(
graphene.String, required=True, description="Value of an attribute."
@@ -677,13 +683,33 @@ class ProductVariantCreate(ModelMutation):
permissions = ("product.manage_products",)
@classmethod
- def clean_product_type_attributes(cls, attributes_qs, attributes_input):
+ def clean_product_type_attributes(cls, info, attributes_qs, attributes_input):
# transform attributes_input list to a dict of slug:value pairs
- attributes_input = {item["slug"]: item["values"] for item in attributes_input}
+ input_slug_map = {} # type: Dict[str, List[str]]
+ input_id_map = {} # type: Dict[int, List[str]]
+
+ for attr_input in attributes_input:
+ attr_id = attr_input.get("id", None)
+ slug = attr_input.get("slug", None)
+ values = attr_input["values"]
+
+ if attr_id:
+ attr_id = from_global_id_strict_type(
+ info, attr_id, only_type=AttributeValue, field="attributes"
+ )
+ input_id_map[attr_id] = values
+ elif slug:
+ input_slug_map[attr_id] = values
+ else:
+ raise ValidationError(
+ {"attributes": "Please provide a value's identifier."}
+ )
for attr in attributes_qs:
- value = attributes_input.get(attr.slug, None)
- if not value:
+ values_by_id = input_id_map.get(attr.id, None)
+ values_by_slug = input_slug_map.get(attr.slug, None)
+
+ if not values_by_id and not values_by_slug:
fieldname = "attributes:%s" % attr.slug
raise ValidationError({fieldname: "This field cannot be blank."})
@@ -702,7 +728,7 @@ class ProductVariantCreate(ModelMutation):
product_type = product.product_type
variant_attrs = product_type.variant_attributes.prefetch_related("values")
try:
- cls.clean_product_type_attributes(variant_attrs, attributes_input)
+ cls.clean_product_type_attributes(info, variant_attrs, attributes_input)
attributes = attributes_to_json(attributes_input, variant_attrs)
except ValueError as e:
raise ValidationError({"attributes": str(e)})
diff --git a/saleor/graphql/product/utils.py b/saleor/graphql/product/utils.py
index 3cbb9d4b54..bcef424d9d 100644
--- a/saleor/graphql/product/utils.py
+++ b/saleor/graphql/product/utils.py
@@ -23,7 +23,13 @@ def attributes_to_json(attribute_value_input: List[dict], attributes_queryset):
a dict of IDs. This function transforms the list of `AttributeValueInput`
objects to this format.
"""
- attributes_map = {attr.slug: attr for attr in attributes_queryset}
+ attributes_map_by_slug = {}
+ attributes_map_by_id = {}
+
+ for attr in attributes_queryset:
+ attributes_map_by_slug[attr.slug] = attr
+ attributes_map_by_id[attr.id] = attr
+
attributes_json = defaultdict(list)
passed_slugs = set()
@@ -33,14 +39,20 @@ def attributes_to_json(attribute_value_input: List[dict], attributes_queryset):
values_map[value.slug] = value.id
for attribute_input in attribute_value_input:
- attr_slug = attribute_input.get("slug")
- passed_slugs.add(attr_slug)
- if attr_slug not in attributes_map:
+ if "slug" in attribute_input:
+ attribute = attributes_map_by_slug.get(attribute_input["slug"])
+ elif "id" in attribute_input:
+ attribute = attributes_map_by_id.get(attribute_input["id"])
+ else:
+ raise ValueError("The value ID or slug was not provided")
+
+ if not attribute:
raise ValueError(
- "Attribute %r doesn't belong to given product type." % (attr_slug,)
+ "The given attribute doesn't belong to given product type."
)
- attribute = attributes_map[attr_slug] # type: models.Attribute
+ passed_slugs.add(attribute.slug)
+
values = attribute_input.get("values")
validate_attribute_input(attribute, values)
@@ -56,8 +68,8 @@ def attributes_to_json(attribute_value_input: List[dict], attributes_queryset):
attributes_json[str(attribute.pk)].append(str(value_id))
# Check that all required attributes were passed
- for missing_slug in attributes_map.keys() ^ passed_slugs:
- attribute = attributes_map[missing_slug] # type: models.Attribute
+ for missing_slug in attributes_map_by_slug.keys() ^ passed_slugs:
+ attribute = attributes_map_by_slug[missing_slug] # type: models.Attribute
validate_attribute_input(attribute, [])
return attributes_json
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 48136ee823..e98e3799fd 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -313,6 +313,8 @@ type AttributeValueDelete {
}
input AttributeValueInput {
+ id: ID
+ name: String
slug: String!
values: [String]!
}
diff --git a/tests/api/test_attributes.py b/tests/api/test_attributes.py
index ff9f70725b..a170dda556 100644
--- a/tests/api/test_attributes.py
+++ b/tests/api/test_attributes.py
@@ -16,6 +16,35 @@ from tests.api.utils import get_graphql_content
def test_attributes_to_json(product, color_attribute):
color_value = color_attribute.values.first()
+ # test transforming slugs of existing attributes to IDs
+ input_data = [{"id": color_attribute.id, "values": [color_value.slug]}]
+ attrs_qs = product.product_type.product_attributes.all()
+ ids = attributes_to_json(input_data, attrs_qs)
+ assert str(color_attribute.pk) in ids
+ assert ids[str(color_attribute.pk)] == [str(color_value.pk)]
+
+ # test creating a new attribute value
+ input_data = [{"id": color_attribute.id, "values": ["Space Grey"]}]
+ ids = attributes_to_json(input_data, attrs_qs)
+ new_value = AttributeValue.objects.get(slug="space-grey")
+ assert str(color_attribute.pk) in ids
+ assert ids[str(color_attribute.pk)] == [str(new_value.pk)]
+
+ # test passing an attribute that doesn't belong to this product raises
+ # an error
+ input_data = [{"id": -1, "values": ["not-a-value"]}]
+ with pytest.raises(ValueError) as exc:
+ attributes_to_json(input_data, attrs_qs)
+ assert exc.value.args == (
+ "The given attribute doesn't belong to given product type.",
+ )
+
+
+# WARNING: Passing by slug will be dropped in a future release
+# This test can be safely removed on the field is dropped.
+def test_attributes_to_json_passing_by_slug(product, color_attribute):
+ color_value = color_attribute.values.first()
+
# test transforming slugs of existing attributes to IDs
input_data = [{"slug": color_attribute.slug, "values": [color_value.slug]}]
attrs_qs = product.product_type.product_attributes.all()
@@ -32,9 +61,12 @@ def test_attributes_to_json(product, color_attribute):
# test passing an attribute that doesn't belong to this product raises
# an error
- input_data = [{"slug": "not-an-attribute", "values": ["not-a-value"]}]
- with pytest.raises(ValueError):
+ input_data = [{"slug": "no-existing", "values": ["not-a-value"]}]
+ with pytest.raises(ValueError) as exc:
attributes_to_json(input_data, attrs_qs)
+ assert exc.value.args == (
+ "The given attribute doesn't belong to given product type.",
+ )
@pytest.mark.parametrize("input", ([{"slug": "color", "values": []}], []))
@@ -52,8 +84,7 @@ def test_attributes_to_json_missing_required_value(product, color_attribute, inp
def test_attributes_to_json_without_values(product, color_attribute):
- # test transforming slugs of existing attributes to IDs
- input_data = [{"slug": color_attribute.slug, "values": []}]
+ input_data = [{"id": color_attribute.id, "values": []}]
attrs_qs = product.product_type.product_attributes.all()
# The attribute should be ignored and raise no error as the value is not required
@@ -71,13 +102,24 @@ def test_attributes_to_json_duplicated_slug(product, color_attribute, size_attri
slug=color_value.slug, name="Duplicated value", attribute=size_attribute
)
- input_data = [{"slug": color_attribute.slug, "values": [color_value.slug]}]
+ input_data = [{"id": color_attribute.id, "values": [color_value.slug]}]
attrs_qs = product.product_type.product_attributes.all()
ids = attributes_to_json(input_data, attrs_qs)
assert str(color_attribute.pk) in ids
assert ids[str(color_attribute.pk)] == [str(color_value.pk)]
+def test_attributes_to_json_missing_value_getter_raises_error(product):
+ # test transforming slugs of existing attributes to IDs
+ input_data = [{"values": []}]
+ attrs_qs = product.product_type.product_attributes.all()
+
+ with pytest.raises(ValueError) as exc:
+ assert not attributes_to_json(input_data, attrs_qs)
+
+ assert exc.value.args == ("The value ID or slug was not provided",)
+
+
def test_get_single_attribute_by_pk(user_api_client, color_attribute_without_values):
attribute_gql_id = graphene.Node.to_global_id(
"Attribute", color_attribute_without_values.id