Skip to content

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

Add migration to generate ProductVariant name from its attributes

Pacu261c3529a0db3
diff --git a/saleor/product/migrations/0059_generate_variant_name_from_attrs.py b/saleor/product/migrations/0059_generate_variant_name_from_attrs.py
new file mode 100644
index 0000000000..5034a3ae63
--- /dev/null
+++ b/saleor/product/migrations/0059_generate_variant_name_from_attrs.py
@@ -0,0 +1,34 @@
+# Generated by Django 2.0.2 on 2018-03-11 18:54
+from django.db import migrations
+
+from saleor.product.utils.attributes import get_attributes_display_map
+
+
+def get_name_from_attributes(variant):
+ attributes = variant.product.product_type.variant_attributes.all()
+ values = get_attributes_display_map(variant, attributes)
+ return ' / '.join(
+ attributechoice.name
+ for attribute_pk, attributechoice in sorted(
+ values.items(), key=lambda x: x[0]))
+
+
+def create_variant_name_based_on_attributes(apps, schema_editor):
+ ProductVariant = apps.get_model('product', 'ProductVariant')
+ for variant in ProductVariant.objects.prefetch_related(
+ 'product__product_type__variant_attributes__values'):
+ new_name = get_name_from_attributes(variant)
+ if variant.name != new_name:
+ variant.name = new_name
+ variant.save()
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [
+ ('product', '0058_auto_20180329_0142'),
+ ]
+
+ operations = [
+ migrations.RunPython(create_variant_name_based_on_attributes)
+ ]