Skip to content

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

Create data migration

fowczarekc8eb4cb6773d
diff --git a/saleor/product/migrations/0108_auto_20191003_0422.py b/saleor/product/migrations/0108_auto_20191003_0422.py
index 83a8baa7a7..2a8955dad6 100644
--- a/saleor/product/migrations/0108_auto_20191003_0422.py
+++ b/saleor/product/migrations/0108_auto_20191003_0422.py
@@ -1,14 +1,46 @@
# Generated by Django 2.2.4 on 2019-10-03 09:22
-from django.db import migrations
+from django.db import migrations, transaction
+from django.db.models import Count
+
+
+def remove_duplicated_attribute_values(apps, schema_editor):
+ AttributeValue = apps.get_model("product", "AttributeValue")
+ duplicated_pk_for_attribute_values = (
+ AttributeValue.objects.values("slug", "attribute")
+ .order_by()
+ .annotate(count_id=Count("id"))
+ .filter(count_id__gt=1)
+ )
+ for duplicated_pk_for_attribute_value in duplicated_pk_for_attribute_values:
+ attribute_values = AttributeValue.objects.filter(
+ attribute=duplicated_pk_for_attribute_value["attribute"],
+ slug=duplicated_pk_for_attribute_value["slug"],
+ )
+ final_value = attribute_values[0]
+ values_to_be_removed = attribute_values[1:]
+ with transaction.atomic():
+ for value_to_be_removed in values_to_be_removed:
+ invalid_assigned_variants = (
+ value_to_be_removed.assignedvariantattribute_set.all()
+ )
+ for invalid_assigned_variant in invalid_assigned_variants:
+ invalid_assigned_variant.values.clear()
+ invalid_assigned_variant.values.add(final_value)
+ ids_to_be_removed = values_to_be_removed.values_list("id", flat=True)
+ AttributeValue.objects.filter(id__in=ids_to_be_removed).delete()
class Migration(migrations.Migration):
+ atomic = False
dependencies = [("product", "0107_attributes_map_to_m2m")]
operations = [
+ migrations.RunPython(
+ remove_duplicated_attribute_values, migrations.RunPython.noop
+ ),
migrations.AlterUniqueTogether(
name="attributevalue", unique_together={("slug", "attribute")}
- )
+ ),
]