Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Change relationship between product types and attributes
Marcin Gębalaee6ffc49561f
diff --git a/saleor/graphql/product/mutations/attributes.py b/saleor/graphql/product/mutations/attributes.pyindex 373cc29e4b..58521f3122 100644--- a/saleor/graphql/product/mutations/attributes.py+++ b/saleor/graphql/product/mutations/attributes.py@@ -100,6 +100,9 @@ class AttributeCreate(AttributeMixin, ModelMutation):attribute = graphene.Field(Attribute, description='A created Attribute.')+ product_type = graphene.Field(+ ProductType,+ description='A product type to which an attribute was added.')class Arguments:id = graphene.ID(@@ -145,7 +148,7 @@ class AttributeCreate(AttributeMixin, ModelMutation):cls.clean_product_type_variant_attributes(product_type, type, errors)if errors:- return cls(errors=errors)+ return AttributeCreate(errors=errors)instance.save()if type == AttributeTypeEnum.VARIANT.name:@@ -153,7 +156,8 @@ class AttributeCreate(AttributeMixin, ModelMutation):else:product_type.product_attributes.add(instance)cls._save_m2m(info, instance, cleaned_input)- return cls.success_response(instance)+ return AttributeCreate(+ attribute=instance, product_type=product_type, errors=errors)class AttributeUpdateInput(graphene.InputObjectType):@@ -170,6 +174,9 @@ class AttributeUpdateInput(graphene.InputObjectType):class AttributeUpdate(AttributeMixin, ModelMutation):ATTRIBUTE_VALUES_FIELD = 'add_values'+ product_type = graphene.Field(+ ProductType, description='A related product type.')+class Arguments:id = graphene.ID(required=True, description='ID of an attribute to update.')@@ -181,10 +188,6 @@ class AttributeUpdate(AttributeMixin, ModelMutation):description = 'Updates attribute.'model = models.Attribute- @classmethod- def user_is_allowed(cls, user, input):- return user.has_perm('product.manage_products')-@classmethoddef clean_remove_values(cls, cleaned_input, instance, errors):"""Check if AttributeValues to be removed are assigned to givendiff --git a/saleor/graphql/product/resolvers.py b/saleor/graphql/product/resolvers.pyindex 9490f19fe9..a746b2682a 100644--- a/saleor/graphql/product/resolvers.py+++ b/saleor/graphql/product/resolvers.py@@ -28,8 +28,8 @@ def resolve_attributes(info, category_id, query):for obj in models.Product.objects.filter(category__in=tree).values_list('product_type_id')}queryset = queryset.filter(- Q(product_types__in=product_types)- | Q(product_variant_types__in=product_types))+ Q(product_type__in=product_types)+ | Q(product_variant_type__in=product_types))return queryset.distinct()diff --git a/saleor/graphql/product/types.py b/saleor/graphql/product/types.pyindex 5eb021b8a6..7ab987b7d8 100644--- a/saleor/graphql/product/types.py+++ b/saleor/graphql/product/types.py@@ -83,7 +83,7 @@ class Attribute(CountableDjangoObjectType):class Meta:description = """Custom attribute of a product. Attributes can beassigned to products and variants at the product type level."""- exclude_fields = ['product_types', 'product_variant_types']+ exclude_fields = []interfaces = [relay.Node]filter_fields = ['id', 'slug']model = models.Attributediff --git a/saleor/product/filters.py b/saleor/product/filters.pyindex 9facd6ed7e..eea2cf4db4 100644--- a/saleor/product/filters.py+++ b/saleor/product/filters.py@@ -88,10 +88,10 @@ class ProductCategoryFilter(ProductFilter):super().__init__(*args, **kwargs)def _get_product_attributes_lookup(self):- return Q(product_types__products__category=self.category)+ return Q(product_type__products__category=self.category)def _get_variant_attributes_lookup(self):- return Q(product_variant_types__products__category=self.category)+ return Q(product_variant_type__products__category=self.category)class ProductCollectionFilter(ProductFilter):@@ -100,7 +100,7 @@ class ProductCollectionFilter(ProductFilter):super().__init__(*args, **kwargs)def _get_product_attributes_lookup(self):- return Q(product_types__products__collections=self.collection)+ return Q(product_type__products__collections=self.collection)def _get_variant_attributes_lookup(self):- return Q(product_variant_types__products__collections=self.collection)+ return Q(product_variant_type__products__collections=self.collection)diff --git a/saleor/product/migrations/0073_auto_20181010_0729.py b/saleor/product/migrations/0073_auto_20181010_0729.pynew file mode 100644index 0000000000..b6435a6d48--- /dev/null+++ b/saleor/product/migrations/0073_auto_20181010_0729.py@@ -0,0 +1,34 @@+# Generated by Django 2.1.2 on 2018-10-10 12:29++from django.db import migrations, models+import django.db.models.deletion+++class Migration(migrations.Migration):++ dependencies = [+ ('product', '0072_auto_20180925_1048'),+ ]++ operations = [+ migrations.AddField(+ model_name='attribute',+ name='product_type',+ field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='temp_product_attributes', to='product.ProductType'),+ ),+ migrations.AddField(+ model_name='attribute',+ name='product_variant_type',+ field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='temp_variant_attributes', to='product.ProductType'),+ ),+ migrations.AlterField(+ model_name='attribute',+ name='name',+ field=models.CharField(max_length=50),+ ),+ migrations.AlterField(+ model_name='attribute',+ name='slug',+ field=models.SlugField(),+ ),+ ]diff --git a/saleor/product/migrations/0074_auto_20181010_0730.py b/saleor/product/migrations/0074_auto_20181010_0730.pynew file mode 100644index 0000000000..2860a3bbd7--- /dev/null+++ b/saleor/product/migrations/0074_auto_20181010_0730.py@@ -0,0 +1,107 @@+# Generated by Django 2.1.2 on 2018-10-10 12:30++from django.db import migrations+++def clone_attribute_data(original_attribute, new_attribute):+ for translation in original_attribute.translations.all():+ new_attribute.translations.create(+ language_code=translation.language_code,+ name=translation.name)++ for value in original_attribute.values.all():+ new_value = new_attribute.values.create(+ name=value.name, value=value.value, slug=value.slug,+ sort_order=value.sort_order)+ for translation in value.translations.all():+ new_value.translations.create(+ language_code=translation.language_code,+ name=translation.name)+++def migrate_attributes(apps, schema_editor):+ Attribute = apps.get_model('product', 'Attribute')+ for attribute in Attribute.objects.all():+ for product_type in attribute.product_types.all():+ new_attr = product_type.temp_product_attributes.create(+ name=attribute.name, slug=attribute.slug)+ clone_attribute_data(attribute, new_attr)+ for product_type in attribute.product_variant_types.all():+ new_attr = product_type.temp_variant_attributes.create(+ name=attribute.name, slug=attribute.slug)+ clone_attribute_data(attribute, new_attr)+++def migrate_attributes_hstore_to_new_ids(apps, schema_editor):+ Product = apps.get_model('product', 'Product')+ Attribute = apps.get_model('product', 'Attribute')+ AttributeValue = apps.get_model('product', 'AttributeValue')++ # Objects maps to avoid DB queries in for-loop+ attributes_map = {str(attr.pk): attr for attr in Attribute.objects.all()}+ values_map = {str(val.pk): val for val in AttributeValue.objects.all()}++ qs = Product.objects.select_related(+ 'product_type').prefetch_related('variants')+ for product in qs:+ # recreate attributes hstore with migrated attributes and values+ if product.attributes:+ new_hstore = {}+ product_type = product.product_type++ for old_attr_pk, old_val_pk in product.attributes.items():+ old_attr = attributes_map.get(old_attr_pk)+ old_val = values_map.get(old_val_pk)+ if not (old_attr and old_val):+ continue+ new_attr = product_type.temp_product_attributes.filter(+ slug=old_attr.slug).first()+ if new_attr:+ new_val = new_attr.values.filter(slug=old_val.slug).first()+ if new_val:+ new_hstore[str(new_attr.pk)] = str(new_val.pk)+ product.attributes = new_hstore+ product.save(update_fields=['attributes'])++ for variant in product.variants.all():+ if variant.attributes:+ new_hstore = {}+ for old_attr_pk, old_val_pk in variant.attributes.items():+ old_attr = attributes_map.get(old_attr_pk)+ old_val = values_map.get(old_val_pk)+ if not (old_attr and old_val):+ continue+ new_attr = product_type.temp_variant_attributes.filter(+ slug=old_attr.slug).first()+ if new_attr:+ new_val = new_attr.values.filter(slug=old_val.slug).first()+ if new_val:+ new_hstore[str(new_attr.pk)] = str(new_val.pk)+ variant.attributes = new_hstore+ variant.save(update_fields=['attributes'])+++def clean_stale_attributes(apps, schema_editor):+ # Remove attributes that have no relation with any product type after+ # all above data migrations were applied.+ Attribute = apps.get_model('product', 'Attribute')+ Attribute.objects.filter(+ product_variant_type__isnull=True).filter(+ product_type__isnull=True).delete()+++class Migration(migrations.Migration):++ dependencies = [+ ('product', '0073_auto_20181010_0729'),+ ]++ operations = [+ migrations.RunPython(+ migrate_attributes, reverse_code=migrations.RunPython.noop),+ migrations.RunPython(+ migrate_attributes_hstore_to_new_ids,+ reverse_code=migrations.RunPython.noop),+ migrations.RunPython(+ clean_stale_attributes, reverse_code=migrations.RunPython.noop)+ ]diff --git a/saleor/product/migrations/0075_auto_20181010_0842.py b/saleor/product/migrations/0075_auto_20181010_0842.pynew file mode 100644index 0000000000..7d67cbcf28--- /dev/null+++ b/saleor/product/migrations/0075_auto_20181010_0842.py@@ -0,0 +1,32 @@+# Generated by Django 2.1.2 on 2018-10-10 13:42++from django.db import migrations, models+import django.db.models.deletion+++class Migration(migrations.Migration):++ dependencies = [+ ('product', '0074_auto_20181010_0730'),+ ]++ operations = [+ migrations.RemoveField(+ model_name='producttype',+ name='product_attributes',+ ),+ migrations.RemoveField(+ model_name='producttype',+ name='variant_attributes',+ ),+ migrations.AlterField(+ model_name='attribute',+ name='product_type',+ field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='product_attributes', to='product.ProductType'),+ ),+ migrations.AlterField(+ model_name='attribute',+ name='product_variant_type',+ field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, related_name='variant_attributes', to='product.ProductType'),+ ),+ ]diff --git a/saleor/product/models.py b/saleor/product/models.pyindex dc1c233618..c7b82f8f77 100644--- a/saleor/product/models.py+++ b/saleor/product/models.py@@ -3,6 +3,7 @@ from decimal import Decimalfrom django.conf import settingsfrom django.contrib.postgres.fields import HStoreField+from django.core.exceptions import ValidationErrorfrom django.core.validators import MinValueValidatorfrom django.db import modelsfrom django.db.models import Q@@ -75,10 +76,6 @@ class CategoryTranslation(SeoModelTranslation):class ProductType(models.Model):name = models.CharField(max_length=128)has_variants = models.BooleanField(default=True)- product_attributes = models.ManyToManyField(- 'Attribute', related_name='product_types', blank=True)- variant_attributes = models.ManyToManyField(- 'Attribute', related_name='product_variant_types', blank=True)is_shipping_required = models.BooleanField(default=False)tax_rate = models.CharField(max_length=128, default=DEFAULT_TAX_RATE_NAME, blank=True,@@ -318,8 +315,14 @@ class ProductVariantTranslation(models.Model):class Attribute(models.Model):- slug = models.SlugField(max_length=50, unique=True)- name = models.CharField(max_length=100)+ slug = models.SlugField(max_length=50)+ name = models.CharField(max_length=50)+ product_type = models.ForeignKey(+ ProductType, related_name='product_attributes', blank=True,+ null=True, on_delete=models.CASCADE)+ product_variant_type = models.ForeignKey(+ ProductType, related_name='variant_attributes', blank=True,+ null=True, on_delete=models.CASCADE)translated = TranslationProxy()