Skip to content

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

Create attributes without specifying associating it to a product type

NyanKiyoshi9c851af76e2d
diff --git a/CHANGELOG.md b/CHANGELOG.md
index bd76919f9f..fa74b4858e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,15 @@
All notable, unreleased changes to this project will be documented in this file. For the released changes, please visit the [Releases](https://github.com/mirumee/saleor/releases) page.
+## [Unreleased Changeset: Attributes]
+
+- The mutations `attributeCreate` and `attributeUpdate`:
+ - They no longer crash if no values were passed. - #4260 by @NyanKiyoshi
+ - They no longer accept the `productType` parameter and no longer return the attribute's `productType` in the root of the response; instead, you should query the attribute's `productType` manually. - #4260 by @NyanKiyoshi
+ - They now accept an optional `slug` input parameter for setting the internal representation of the attribute instead of always generating it. This allows users to have multiple attributes with the same name but that are different things or set of values. - #4260 by @NyanKiyoshi
+- The `Attribute` model:
+ - They now always unique, instead of being unique only into a given product type. - #4260 by @NyanKiyoshi
+
## [Unreleased]
- Fix product type taxes select - #4453 by @benekex2
diff --git a/saleor/graphql/product/mutations/attributes.py b/saleor/graphql/product/mutations/attributes.py
index aff11dec60..20fe9c9ea1 100644
--- a/saleor/graphql/product/mutations/attributes.py
+++ b/saleor/graphql/product/mutations/attributes.py
@@ -1,6 +1,5 @@
import graphene
from django.core.exceptions import ValidationError
-from django.db.models import Q
from django.template.defaultfilters import slugify
from ....product import models
@@ -12,7 +11,6 @@ from ...core.mutations import (
)
from ...product.types import ProductType
from ..descriptions import AttributeDescriptions, AttributeValueDescriptions
-from ..enums import AttributeTypeEnum
from ..types import Attribute
@@ -23,6 +21,7 @@ class AttributeValueCreateInput(graphene.InputObjectType):
class AttributeCreateInput(graphene.InputObjectType):
name = graphene.String(required=True, description=AttributeDescriptions.NAME)
+ slug = graphene.String(required=False, description=AttributeDescriptions.SLUG)
values = graphene.List(
AttributeValueCreateInput, description=AttributeDescriptions.VALUES
)
@@ -30,6 +29,7 @@ class AttributeCreateInput(graphene.InputObjectType):
class AttributeUpdateInput(graphene.InputObjectType):
name = graphene.String(description=AttributeDescriptions.NAME)
+ slug = graphene.String(description=AttributeDescriptions.SLUG)
remove_values = graphene.List(
graphene.ID,
name="removeValues",
@@ -44,7 +44,7 @@ class AttributeUpdateInput(graphene.InputObjectType):
class AttributeMixin:
@classmethod
- def check_unique_values(cls, values_input, attribute):
+ def check_values_are_unique(cls, values_input, attribute):
# Check values uniqueness in case of creating new attribute.
existing_values = attribute.values.values_list("slug", flat=True)
for value_data in values_input:
@@ -70,7 +70,11 @@ class AttributeMixin:
Slugs are created from given names and checked for uniqueness within
an attribute.
"""
- values_input = cleaned_input[cls.ATTRIBUTE_VALUES_FIELD]
+ values_input = cleaned_input.get(cls.ATTRIBUTE_VALUES_FIELD)
+
+ if values_input is None:
+ return
+
for value_data in values_input:
value_data["slug"] = slugify(value_data["name"])
attribute_value = models.AttributeValue(**value_data, attribute=attribute)
@@ -82,29 +86,24 @@ class AttributeMixin:
continue
for msg in validation_errors.message_dict[field]:
raise ValidationError({cls.ATTRIBUTE_VALUES_FIELD: msg})
- cls.check_unique_values(values_input, attribute)
+ cls.check_values_are_unique(values_input, attribute)
@classmethod
- def clean_attribute(cls, instance, cleaned_input, product_type=None):
- if "name" in cleaned_input:
- slug = slugify(cleaned_input["name"])
- elif instance.pk:
- slug = instance.slug
- else:
- raise ValidationError({"name": "This field cannot be blank."})
- cleaned_input["slug"] = slug
-
- if not product_type:
- product_type = instance.product_type
-
- query = models.Attribute.objects.filter(slug=slug).filter(
- Q(product_type=product_type) | Q(product_variant_type=product_type)
- )
- query = query.exclude(pk=getattr(instance, "pk", None))
+ def clean_attribute(cls, instance, cleaned_input):
+ input_slug = cleaned_input.get("slug", None)
+ if input_slug is None:
+ cleaned_input["slug"] = slugify(cleaned_input["name"])
+ elif input_slug == "":
+ raise ValidationError({"slug": "The attribute's slug cannot be blank."})
+
+ query = models.Attribute.objects.filter(slug=cleaned_input["slug"])
+
+ if instance.pk:
+ query = query.exclude(pk=instance.pk)
+
if query.exists():
- raise ValidationError(
- {"name": "Attribute already exists within this product type."}
- )
+ raise ValidationError({"slug": "This attribute's slug already exists."})
+
return cleaned_input
@classmethod
@@ -116,60 +115,49 @@ class AttributeMixin:
class AttributeCreate(AttributeMixin, ModelMutation):
+ # Needed by AttributeMixin,
+ # represents the input name for the passed list of values
ATTRIBUTE_VALUES_FIELD = "values"
- attribute = graphene.Field(Attribute, description="A created Attribute.")
- product_type = graphene.Field(
- ProductType, description="A product type to which an attribute was added."
- )
+ attribute = graphene.Field(Attribute, description="The created attribute.")
class Arguments:
- id = graphene.ID(
- required=True,
- description="ID of the ProductType to create an attribute for.",
- )
- type = AttributeTypeEnum(
- required=True,
- description=(
- "Type of an Attribute, if should be created for Products "
- "or Variants of this ProductType."
- ),
- )
input = AttributeCreateInput(
required=True, description="Fields required to create an attribute."
)
class Meta:
- description = "Creates an attribute."
model = models.Attribute
+ description = "Creates an attribute."
permissions = ("product.manage_products",)
@classmethod
def perform_mutation(cls, _root, info, **data):
- product_type = cls.get_node_or_error(
- info, data.get("id"), only_type=ProductType
- )
instance = models.Attribute()
+ # Do cleaning and uniqueness checks
cleaned_input = cls.clean_input(info, instance, data.get("input"))
- cls.clean_attribute(instance, cleaned_input, product_type=product_type)
+ cls.clean_attribute(instance, cleaned_input)
cls.clean_values(cleaned_input, instance)
+
+ # Construct the attribute
instance = cls.construct_instance(instance, cleaned_input)
cls.clean_instance(instance)
+ # Commit it
instance.save()
- if data.get("type") == AttributeTypeEnum.VARIANT.name:
- product_type.variant_attributes.add(instance)
- else:
- product_type.product_attributes.add(instance)
cls._save_m2m(info, instance, cleaned_input)
- return AttributeCreate(attribute=instance, product_type=product_type)
+
+ # Return the attribute that was created
+ return AttributeCreate(attribute=instance)
class AttributeUpdate(AttributeMixin, ModelMutation):
+ # Needed by AttributeMixin,
+ # represents the input name for the passed list of values
ATTRIBUTE_VALUES_FIELD = "add_values"
- product_type = graphene.Field(ProductType, description="A related product type.")
+ attribute = graphene.Field(Attribute, description="The updated attribute.")
class Arguments:
id = graphene.ID(required=True, description="ID of an attribute to update.")
@@ -178,8 +166,8 @@ class AttributeUpdate(AttributeMixin, ModelMutation):
)
class Meta:
- description = "Updates attribute."
model = models.Attribute
+ description = "Updates attribute."
permissions = ("product.manage_products",)
@classmethod
@@ -202,17 +190,22 @@ class AttributeUpdate(AttributeMixin, ModelMutation):
def perform_mutation(cls, _root, info, id, input):
instance = cls.get_node_or_error(info, id, only_type=Attribute)
+ # Do cleaning and uniqueness checks
cleaned_input = cls.clean_input(info, instance, input)
- product_type = instance.product_type
- cls.clean_attribute(instance, cleaned_input, product_type=product_type)
+ cls.clean_attribute(instance, cleaned_input)
cls.clean_values(cleaned_input, instance)
cls.clean_remove_values(cleaned_input, instance)
+
+ # Construct the attribute
instance = cls.construct_instance(instance, cleaned_input)
cls.clean_instance(instance)
+ # Commit it
instance.save()
cls._save_m2m(info, instance, cleaned_input)
- return AttributeUpdate(attribute=instance, product_type=product_type)
+
+ # Return the attribute that was created
+ return AttributeUpdate(attribute=instance)
class AttributeDelete(ModelDeleteMutation):
@@ -222,8 +215,8 @@ class AttributeDelete(ModelDeleteMutation):
id = graphene.ID(required=True, description="ID of an attribute to delete.")
class Meta:
- description = "Deletes an attribute."
model = models.Attribute
+ description = "Deletes an attribute."
permissions = ("product.manage_products",)
@classmethod
@@ -266,7 +259,7 @@ class AttributeClearPrivateMeta(ClearMetaBaseMutation):
class AttributeValueCreate(ModelMutation):
- attribute = graphene.Field(Attribute, description="A related Attribute.")
+ attribute = graphene.Field(Attribute, description="The updated attribute.")
class Arguments:
attribute_id = graphene.ID(
@@ -279,8 +272,8 @@ class AttributeValueCreate(ModelMutation):
)
class Meta:
- description = "Creates a value for an attribute."
model = models.AttributeValue
+ description = "Creates a value for an attribute."
permissions = ("product.manage_products",)
@classmethod
@@ -304,7 +297,7 @@ class AttributeValueCreate(ModelMutation):
class AttributeValueUpdate(ModelMutation):
- attribute = graphene.Field(Attribute, description="A related Attribute.")
+ attribute = graphene.Field(Attribute, description="The updated attribute.")
class Arguments:
id = graphene.ID(
@@ -315,8 +308,8 @@ class AttributeValueUpdate(ModelMutation):
)
class Meta:
- description = "Updates value of an attribute."
model = models.AttributeValue
+ description = "Updates value of an attribute."
permissions = ("product.manage_products",)
@classmethod
@@ -334,14 +327,14 @@ class AttributeValueUpdate(ModelMutation):
class AttributeValueDelete(ModelDeleteMutation):
- attribute = graphene.Field(Attribute, description="A related Attribute.")
+ attribute = graphene.Field(Attribute, description="The updated attribute.")
class Arguments:
id = graphene.ID(required=True, description="ID of a value to delete.")
class Meta:
- description = "Deletes a value of an attribute."
model = models.AttributeValue
+ description = "Deletes a value of an attribute."
permissions = ("product.manage_products",)
@classmethod
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index a150be68a4..15ab5670bc 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -182,11 +182,11 @@ type AttributeCountableEdge {
type AttributeCreate {
errors: [Error!]
attribute: Attribute
- productType: ProductType
}
input AttributeCreateInput {
name: String!
+ slug: String
values: [AttributeValueCreateInput]
}
@@ -214,19 +214,14 @@ type AttributeTranslation implements Node {
language: LanguageDisplay!
}
-enum AttributeTypeEnum {
- PRODUCT
- VARIANT
-}
-
type AttributeUpdate {
errors: [Error!]
- productType: ProductType
attribute: Attribute
}
input AttributeUpdateInput {
name: String
+ slug: String
removeValues: [ID]
addValues: [AttributeValueCreateInput]
}
@@ -1691,7 +1686,7 @@ type Mutations {
shippingZoneDelete(id: ID!): ShippingZoneDelete
shippingZoneBulkDelete(ids: [ID]!): ShippingZoneBulkDelete
shippingZoneUpdate(id: ID!, input: ShippingZoneInput!): ShippingZoneUpdate
- attributeCreate(id: ID!, input: AttributeCreateInput!, type: AttributeTypeEnum!): AttributeCreate
+ attributeCreate(input: AttributeCreateInput!): AttributeCreate
attributeDelete(id: ID!): AttributeDelete
attributeBulkDelete(ids: [ID]!): AttributeBulkDelete
attributeUpdate(id: ID!, input: AttributeUpdateInput!): AttributeUpdate
diff --git a/saleor/product/migrations/0094_auto_20190611_0952.py b/saleor/product/migrations/0094_auto_20190611_0952.py
new file mode 100644
index 0000000000..e517d3a0e7
--- /dev/null
+++ b/saleor/product/migrations/0094_auto_20190611_0952.py
@@ -0,0 +1,29 @@
+# Generated by Django 2.2.2 on 2019-06-11 14:52
+
+from django.db import migrations, models
+from django.db.models import Count
+
+
+def ensure_attribute_slugs_are_unique_or_fix(apps, schema_editor):
+ Attribute = apps.get_model("product", "Attribute") # noqa
+ non_unique_slugs = (
+ Attribute.objects.values_list("slug", flat=True)
+ .annotate(slug_count=Count("slug"))
+ .filter(slug_count__gt=1)
+ )
+ non_unique_attrs = Attribute.objects.filter(slug__in=list(non_unique_slugs))
+ for suffix, attr in enumerate(non_unique_attrs):
+ attr.slug += f"__{suffix}"
+ attr.save(update_fields=["slug"])
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [("product", "0093_auto_20190521_0124")]
+
+ operations = [
+ migrations.RunPython(ensure_attribute_slugs_are_unique_or_fix),
+ migrations.AlterField(
+ model_name="attribute", name="slug", field=models.SlugField(unique=True)
+ ),
+ ]
diff --git a/saleor/product/models.py b/saleor/product/models.py
index 1d61b9363a..8eca8bc1b3 100644
--- a/saleor/product/models.py
+++ b/saleor/product/models.py
@@ -426,7 +426,7 @@ class DigitalContentUrl(models.Model):
class Attribute(ModelWithMetadata):
- slug = models.SlugField(max_length=50)
+ slug = models.SlugField(max_length=50, unique=True)
name = models.CharField(max_length=50)
product_type = models.ForeignKey(
ProductType,
diff --git a/tests/api/test_attributes.py b/tests/api/test_attributes.py
index 9a1cbadb8f..5e9f4a5143 100644
--- a/tests/api/test_attributes.py
+++ b/tests/api/test_attributes.py
@@ -3,7 +3,7 @@ import pytest
from django.db.models import Q
from django.template.defaultfilters import slugify
-from saleor.graphql.product.enums import AttributeTypeEnum, AttributeValueType
+from saleor.graphql.product.enums import AttributeValueType
from saleor.graphql.product.types.attributes import resolve_attribute_value_type
from saleor.graphql.product.utils import attributes_to_hstore
from saleor.product.models import Attribute, AttributeValue, Category
@@ -139,61 +139,103 @@ def test_attributes_in_collection_query(user_api_client, sale):
CREATE_ATTRIBUTES_QUERY = """
- mutation createAttribute(
- $name: String!, $values: [AttributeValueCreateInput],
- $id: ID!, $type: AttributeTypeEnum!) {
- attributeCreate(
- id: $id, type: $type, input: {name: $name, values: $values}) {
- errors {
- field
- message
- }
- attribute {
- name
- slug
- values {
+ mutation createAttribute($name: String!, $values: [AttributeValueCreateInput]) {
+ attributeCreate(input: {name: $name, values: $values}) {
+ errors {
+ field
+ message
+ }
+ attribute {
name
slug
+ values {
+ name
+ slug
+ }
+ productType {
+ id
+ }
}
}
- productType {
- id
- name
- }
}
-}
"""
def test_create_attribute_and_attribute_values(
- staff_api_client, permission_manage_products, product_type
+ staff_api_client, permission_manage_products
):
query = CREATE_ATTRIBUTES_QUERY
- node_id = graphene.Node.to_global_id("ProductType", product_type.id)
attribute_name = "Example name"
name = "Value name"
- variables = {
- "name": attribute_name,
- "id": node_id,
- "type": AttributeTypeEnum.PRODUCT.name,
- "values": [{"name": name, "value": "#1231"}],
- }
+ variables = {"name": attribute_name, "values": [{"name": name, "value": "#1231"}]}
response = staff_api_client.post_graphql(
query, variables, permissions=[permission_manage_products]
)
content = get_graphql_content(response)
assert not content["data"]["attributeCreate"]["errors"]
data = content["data"]["attributeCreate"]
- assert data["attribute"]["name"] == attribute_name
- assert data["attribute"]["slug"] == slugify(attribute_name)
+ # Check if the attribute was correctly created
+ assert data["attribute"]["name"] == attribute_name
+ assert data["attribute"]["slug"] == slugify(
+ attribute_name
+ ), "The default slug should be the slugified name"
+ assert (
+ data["attribute"]["productType"] is None
+ ), "The attribute should not have been assigned to a product type"
+
+ # Check if the attribute values were correctly created
assert len(data["attribute"]["values"]) == 1
assert data["attribute"]["values"][0]["name"] == name
assert data["attribute"]["values"][0]["slug"] == slugify(name)
- attribute = Attribute.objects.get(name=attribute_name)
- assert attribute in product_type.product_attributes.all()
- assert data["productType"]["name"] == product_type.name
+
+
+ "input_slug, expected_slug, expected_error",
+ (
+ ("my-slug", "my-slug", []),
+ (None, "my-name", []),
+ (
+ "",
+ None,
+ [{"field": "slug", "message": "The attribute's slug cannot be blank."}],
+ ),
+ ),
+)
+def test_create_attribute_with_given_slug(
+ staff_api_client,
+ permission_manage_products,
+ input_slug,
+ expected_slug,
+ expected_error,
+):
+ staff_api_client.user.user_permissions.add(permission_manage_products)
+ query = """
+ mutation createAttribute(
+ $name: String!, $slug: String) {
+ attributeCreate(input: {name: $name, slug: $slug}) {
+ errors {
+ field
+ message
+ }
+ attribute {
+ slug
+ }
+ }
+ }
+ """
+
+ attribute_name = "My Name"
+ variables = {"name": attribute_name, "slug": input_slug}
+ content = get_graphql_content(staff_api_client.post_graphql(query, variables))
+
+ # Check if the error is as expected: null or something else
+ assert content["data"]["attributeCreate"]["errors"] == expected_error
+
+ # Check if the slug was correctly set if no error was expected
+ if expected_error is None:
+ assert content["data"]["attributeCreate"]["attribute"]["slug"] == expected_slug
@pytest.mark.parametrize(
@@ -212,11 +254,8 @@ def test_create_attribute_and_attribute_values_errors(
product_type,
):
query = CREATE_ATTRIBUTES_QUERY
- node_id = graphene.Node.to_global_id("ProductType", product_type.id)
variables = {
"name": "Example name",
- "id": node_id,
- "type": AttributeTypeEnum.PRODUCT.name,
"values": [
{"name": name_1, "value": "#1231"},
{"name": name_2, "value": "#121"},
@@ -232,48 +271,6 @@ def test_create_attribute_and_attribute_values_errors(
assert errors[0]["message"] == error_msg
-def test_create_variant_attribute(
- staff_api_client, permission_manage_products, product_type
-):
- product_type.has_variants = True
- product_type.save()
-
- query = CREATE_ATTRIBUTES_QUERY
- node_id = graphene.Node.to_global_id("ProductType", product_type.id)
- attribute_name = "Example name"
- variables = {
- "name": attribute_name,
- "id": node_id,
- "type": AttributeTypeEnum.VARIANT.name,
- "values": [],
- }
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_products]
- )
- content = get_graphql_content(response)
- assert not content["data"]["attributeCreate"]["errors"]
- attribute = Attribute.objects.get(name=attribute_name)
- assert attribute in product_type.variant_attributes.all()
-
-
-def test_create_attribute_incorrect_product_type_id(
- staff_api_client, permission_manage_products, product_type
-):
- query = CREATE_ATTRIBUTES_QUERY
- variables = {
- "name": "Example name",
- "id": "incorrect-id",
- "type": AttributeTypeEnum.PRODUCT.name,
- "values": [],
- }
- response = staff_api_client.post_graphql(
- query, variables, permissions=[permission_manage_products]
- )
- content = get_graphql_content(response)
- errors = content["data"]["attributeCreate"]["errors"]
- assert errors[0]["field"] == "id"
-
-
UPDATE_ATTRIBUTE_QUERY = """
mutation updateAttribute(
$id: ID!, $name: String!, $addValues: [AttributeValueCreateInput]!,
@@ -294,10 +291,9 @@ UPDATE_ATTRIBUTE_QUERY = """
name
slug
}
- }
- productType {
- id
- name
+ productType {
+ id
+ }
}
}
}
@@ -305,7 +301,7 @@ UPDATE_ATTRIBUTE_QUERY = """
def test_update_attribute_name(
- staff_api_client, color_attribute, product_type, permission_manage_products
+ staff_api_client, color_attribute, permission_manage_products
):
query = UPDATE_ATTRIBUTE_QUERY
attribute = color_attribute
@@ -319,7 +315,7 @@ def test_update_attribute_name(
attribute.refresh_from_db()
data = content["data"]["attributeUpdate"]
assert data["attribute"]["name"] == name == attribute.name
- assert data["productType"]["name"] == attribute.product_type.name
+ assert data["attribute"]["productType"] is None
def test_update_attribute_remove_and_add_values(