Skip to content

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

Create attribute value if provided one does not exists

Adam Janik484ac794d718
diff --git a/saleor/dashboard/graphql/utils.py b/saleor/dashboard/graphql/utils.py
index acca5e9bd1..cc3386ea76 100644
--- a/saleor/dashboard/graphql/utils.py
+++ b/saleor/dashboard/graphql/utils.py
@@ -1,4 +1,7 @@
-from saleor.product import models
+from django.utils.encoding import smart_text
+from django.utils.text import slugify
+
+from ...product.models import AttributeChoiceValue, ProductAttribute
def get_attributes_dict_from_list(attributes):
@@ -8,18 +11,26 @@ def get_attributes_dict_from_list(attributes):
Takes list on form [{"slug": "attr_slug", "value": "attr_value"}, {...}]
and converts into dictionary {attr_pk: value_pk}
"""
-
attr_ids = {}
attr_slug_id = dict(
- models.ProductAttribute.objects.values_list('slug', 'id'))
+ ProductAttribute.objects.values_list('slug', 'id'))
value_slug_id = dict(
- models.AttributeChoiceValue.objects.values_list('name', 'id'))
+ AttributeChoiceValue.objects.values_list('name', 'id'))
for attribute in attributes:
attr_slug = attribute.get('slug')
if attr_slug not in attr_slug_id:
raise ValueError(
'Unknown attribute slug: %r' % (attr_slug,))
- attr_value = attribute.get('value')
- attr_ids[attr_slug_id.get(
- attr_slug)] = value_slug_id.get(attr_value)
+ value = attribute.get('value')
+ if value:
+ if not value_slug_id.get(value):
+ attr = ProductAttribute.objects.get(slug='size')
+ value = AttributeChoiceValue(
+ attribute_id=attr.pk, name=value, slug=slugify(value))
+ value.save()
+ attr_ids[smart_text(
+ attr_slug_id.get(attr_slug))] = smart_text(value.pk)
+ else:
+ attr_ids[smart_text(attr_slug_id.get(attr_slug))] = smart_text(
+ value_slug_id.get(value))
return attr_ids
diff --git a/tests/dashboard/test_graphql.py b/tests/dashboard/test_graphql.py
index 5451f95f67..09e9a18965 100644
--- a/tests/dashboard/test_graphql.py
+++ b/tests/dashboard/test_graphql.py
@@ -4,6 +4,7 @@ from unittest.mock import patch
import graphene
import pytest
from django.shortcuts import reverse
+from django.utils.text import slugify
from saleor.dashboard.graphql.mutations import (
ModelFormMutation, ModelFormUpdateMutation)
@@ -353,7 +354,8 @@ def test_create_product(
assert data['product']['isPublished'] == product_isPublished
assert data['product']['productType']['name'] == product_type.name
assert data['product']['category']['name'] == default_category.name
- assert data['product']['attributes'][1]['value'] == None
+ assert data['product']['attributes'][1]['value'] == slugify(
+ non_existent_attr_value)
assert data['product']['attributes'][0]['value'] == color_value_slug