Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Implement setting up product attributes during creation a new one
Adam Janik3001d96de3df
diff --git a/saleor/dashboard/graphql/product/forms.py b/saleor/dashboard/graphql/product/forms.pyindex de802e414a..fe8849eb3d 100644--- a/saleor/dashboard/graphql/product/forms.py+++ b/saleor/dashboard/graphql/product/forms.py@@ -1,6 +1,6 @@from django import forms+from ....product.models import Product-from ....graphql.product.fields import AttributeFieldclass ProductForm(forms.ModelForm):diff --git a/saleor/dashboard/graphql/product/mutations.py b/saleor/dashboard/graphql/product/mutations.pyindex 031c79288f..7fd84b439b 100644--- a/saleor/dashboard/graphql/product/mutations.py+++ b/saleor/dashboard/graphql/product/mutations.py@@ -1,13 +1,14 @@import graphene+from graphene.types import InputObjectTypefrom ....graphql.product.types import Category, ProductTypefrom ....graphql.utils import get_nodefrom ....product import modelsfrom ...category.forms import CategoryForm-from .forms import ProductFormfrom ..mutations import (BaseMutation, ModelDeleteMutation, ModelFormMutation,- ModelFormUpdateMutation, StaffMemberRequiredMutation)+ ModelFormUpdateMutation, StaffMemberRequiredMutation, convert_form_errors)+from .forms import ProductFormclass CategoryCreateMutation(StaffMemberRequiredMutation, ModelFormMutation):@@ -45,24 +46,17 @@ class CategoryDelete(StaffMemberRequiredMutation, ModelDeleteMutation):class Meta:model = models.Category-from graphene.types import InputObjectType-class ValuesInput(InputObjectType):name = graphene.String(required=True)value = graphene.String(required=True)-class AttributesInput(InputObjectType):- attrvalues = graphene.List(ValuesInput)--class ProductCreateMutation(ModelFormMutation):class Arguments:product_type_id = graphene.ID()category_id = graphene.ID()- # TODO: add here optional attributes field- attributes = AttributesInput(required=False)+ attributes = graphene.Argument(graphene.List(ValuesInput))class Meta:form_class = ProductForm@@ -80,3 +74,33 @@ class ProductCreateMutation(ModelFormMutation):kwargs['data']['product_type'] = product_type.idkwargs['data']['category'] = category.idreturn kwargs++ @classmethod+ def mutate(cls, root, info, **kwargs):+ form_kwargs = cls.get_form_kwargs(root, info, **kwargs)+ attributes = form_kwargs.get('data').pop('attributes', None)+ if attributes:+ attr_ids = {}+ attr_name_id = dict(+ models.ProductAttribute.objects.values_list('name', 'id'))+ value_name_id = dict(+ models.AttributeChoiceValue.objects.values_list('name', 'id'))+ for attribute in attributes:+ attr_name = attribute.get('name')+ if attr_name not in attr_name_id:+ raise ValueError(+ 'Unknown attribute name: %r' % (attr_name,))+ attr_value = attribute.get('value')+ attr_ids[attr_name_id.get(+ attr_name)] = value_name_id.get(attr_value)++ form = cls._meta.form_class(**form_kwargs)+ if form.is_valid():+ instance = form.instance+ instance.attributes = attr_ids+ instance.save()+ kwargs = {cls._meta.return_field_name: instance}+ return cls(errors=[], **kwargs)+ errors = convert_form_errors(form)+ return cls(errors=errors)+ return super().mutate(root, info, **kwargs)diff --git a/saleor/dashboard/product/forms.py b/saleor/dashboard/product/forms.pyindex 2fb267df6a..4a4825935c 100644--- a/saleor/dashboard/product/forms.py+++ b/saleor/dashboard/product/forms.py@@ -15,7 +15,7 @@ from ...product.models import (ProductImage, ProductType, ProductVariant, Stock, StockLocation,VariantImage)from ...product.thumbnails import create_product_thumbnails-from ..forms import OrderedModelMultipleChoiceField, ModelChoiceOrCreationField+from ..forms import ModelChoiceOrCreationField, OrderedModelMultipleChoiceFieldfrom ..seo.fields import SeoDescriptionField, SeoTitleFieldfrom ..seo.utils import prepare_seo_descriptionfrom ..widgets import RichTextEditorWidgetdiff --git a/saleor/graphql/product/types.py b/saleor/graphql/product/types.pyindex ed55ab6390..aec98886fa 100644--- a/saleor/graphql/product/types.py+++ b/saleor/graphql/product/types.py@@ -11,7 +11,27 @@ from ..core.types import (CountableDjangoObjectType, Money, TaxedMoney, TaxedMoneyRange)from ..utils import get_nodefrom .filters import ProductFilterSet-from .fields import AttributeField+++class ProductAttributes(graphene.ObjectType):+ name = graphene.String(default_value=None)+ value = graphene.String(default_value=None)+++class ProductVariant(CountableDjangoObjectType):+ stock_quantity = graphene.Int()+ price_override = graphene.Field(Money)+ attributes = graphene.List(ProductAttributes)++ class Meta:+ model = models.ProductVariant+ interfaces = [relay.Node]++ def resolve_stock_quantity(self, info):+ return self.get_stock_quantity()++ def resolve_attributes(self, info):+ return resolve_instance_attributes(instance=self, info=info)class ProductAvailability(graphene.ObjectType):@@ -32,6 +52,7 @@ class Product(CountableDjangoObjectType):description='The size of a thumbnail, for example 255x255'))availability = graphene.Field(ProductAvailability)price = graphene.Field(Money)+ attributes = graphene.List(ProductAttributes)class Meta:model = models.Product@@ -51,6 +72,9 @@ class Product(CountableDjangoObjectType):self, context.discounts, context.currency)return ProductAvailability(**availability._asdict())+ def resolve_attributes(self, info):+ return resolve_instance_attributes(instance=self, info=info)+class ProductType(CountableDjangoObjectType):products = DjangoFilterConnectionField(@@ -96,34 +120,7 @@ class Category(CountableDjangoObjectType):return qs.distinct()-class ProductAttributes(graphene.ObjectType):- name = graphene.String()- value = graphene.String()--class ProductVariant(CountableDjangoObjectType):- stock_quantity = graphene.Int()- price_override = graphene.Field(Money)- attributes = graphene.List(ProductAttributes)-- class Meta:- model = models.ProductVariant- interfaces = [relay.Node]-- def resolve_stock_quantity(self, info):- return self.get_stock_quantity()-- def resolve_attributes(self, info):- product_attributes = dict(- models.ProductAttribute.objects.values_list('id', 'slug'))- attribute_values = dict(- models.AttributeChoiceValue.objects.values_list('id', 'slug'))- attribute_list = []- for k, v in self.attributes.items():- name = product_attributes.get(int(k))- value = attribute_values.get(int(v))- attribute_list.append(ProductAttributes(name=name, value=value))- return attribute_listclass ProductImage(CountableDjangoObjectType):url = graphene.String(size=graphene.String())@@ -156,6 +153,22 @@ class ProductAttribute(CountableDjangoObjectType):return self.values.all()+def resolve_instance_attributes(instance, info):+ product_attributes = dict(+ models.ProductAttribute.objects.values_list('id', 'slug'))+ attribute_values = dict(+ models.AttributeChoiceValue.objects.values_list('id', 'slug'))+ attribute_list = []+ if instance.attributes.items():+ for k, v in instance.attributes.items():+ value = None+ name = product_attributes.get(int(k))+ if v:+ value = attribute_values.get(int(v))+ attribute_list.append(ProductAttributes(name=name, value=value))+ return attribute_list++def resolve_categories(info, level=None):qs = models.Category.objects.all()if level is not None:diff --git a/saleor/product/migrations/0053_auto_20180323_0445.py b/saleor/product/migrations/0053_auto_20180323_0445.pynew file mode 100644index 0000000000..5107ebcfef--- /dev/null+++ b/saleor/product/migrations/0053_auto_20180323_0445.py@@ -0,0 +1,24 @@+# Generated by Django 2.0.3 on 2018-03-23 09:45++import django.contrib.postgres.fields.hstore+from django.db import migrations+++class Migration(migrations.Migration):++ dependencies = [+ ('product', '0052_slug_field_length'),+ ]++ operations = [+ migrations.AlterField(+ model_name='product',+ name='attributes',+ field=django.contrib.postgres.fields.hstore.HStoreField(blank=True, default={}),+ ),+ migrations.AlterField(+ model_name='productvariant',+ name='attributes',+ field=django.contrib.postgres.fields.hstore.HStoreField(blank=True, default={}),+ ),+ ]diff --git a/saleor/product/models.py b/saleor/product/models.pyindex 005148ce74..38d2b75a75 100644--- a/saleor/product/models.py+++ b/saleor/product/models.py@@ -186,7 +186,7 @@ class ProductVariant(models.Model):blank=True, null=True)product = models.ForeignKey(Product, related_name='variants', on_delete=models.CASCADE)- attributes = HStoreField(default={})+ attributes = HStoreField(default={}, blank=True)images = models.ManyToManyField('ProductImage', through='VariantImage')class Meta: