Skip to content

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

Squash and finalize migrations from WiP

NyanKiyoshi69359f6fc697
diff --git a/saleor/product/migrations/0102_migrate_data_enterprise_grade_attributes.py b/saleor/product/migrations/0102_migrate_data_enterprise_grade_attributes.py
new file mode 100644
index 0000000000..dae3fb1c4a
--- /dev/null
+++ b/saleor/product/migrations/0102_migrate_data_enterprise_grade_attributes.py
@@ -0,0 +1,132 @@
+from dataclasses import dataclass
+
+from django.db import migrations
+from django.db.models import Count, F, Window
+from django.db.models.functions import RowNumber
+
+
+def ensure_attribute_slugs_are_unique_or_fix(apps, schema_editor):
+ """Ensure all attribute slugs are unique.
+
+ Instead of being unique within a product type, attributes' slug are now globally
+ unique. For that, we look for duplicate slugs and rename them with a new suffix.
+ """
+ Attribute = apps.get_model("product", "Attribute") # noqa
+ non_unique_slugs = (
+ Attribute.objects.values_list("slug", flat=True)
+ .annotate(slug_count=Count("slug"))
+ .filter(slug_count__gt=1)
+ )
+ non_unique_attrs = Attribute.objects.filter(slug__in=list(non_unique_slugs))
+ for suffix, attr in enumerate(non_unique_attrs):
+ attr.slug += f"__{suffix}"
+ attr.save(update_fields=["slug"])
+
+
+def migrate_attributes_to_list(model_name):
+ """Migrate HStore attributes configuration to JSONB with a list of values."""
+
+ def make_migration(apps, schema):
+ Model = apps.get_model("product", model_name)
+
+ for instance in Model.objects.all():
+ new_attributes = {}
+
+ for k, v in instance.attributes.items():
+ if not isinstance(v, list):
+ new_attributes[k] = [v]
+ else:
+ new_attributes[k] = v
+
+ instance.attributes = new_attributes
+ instance.save(update_fields=["attributes"])
+
+ return make_migration
+
+
+def remove_duplicates_products_in_collections(apps, schema_editor):
+ """Remove any duplicated M2M, and keep only one of them.
+
+ First we select the duplicates, by grouping them and counting them:
+
+ SELECT
+ collection_id, product_id, COUNT(*)
+ FROM
+ public.product_collectionproduct
+ GROUP BY
+ collection_id, product_id
+ HAVING
+ COUNT(*) > 1
+
+ Then we retrieve all of them except one (LIMIT = `duplicate_count - 1`).
+
+ Once we have them, we delete each of them manually (cannot directly delete by using
+ LIMIT).
+ """
+
+ CollectionProduct = apps.get_model("product", "CollectionProduct")
+
+ duplicates = (
+ CollectionProduct.objects.values("collection_id", "product_id")
+ .annotate(duplicate_count=Count("*"))
+ .filter(duplicate_count__gt=1)
+ )
+
+ for duplicate in duplicates:
+ dup_count = duplicate.pop("duplicate_count")
+ delete_limit = dup_count - 1
+ entries_to_delete = CollectionProduct.objects.filter(**duplicate)[:delete_limit]
+ for entry in entries_to_delete:
+ entry.delete()
+
+
+@dataclass(frozen=True)
+class NewCollectionProductSortOrder:
+ pk: int
+ sort_order: int
+
+
+def ensure_model_is_ordered(model_name):
+ def reorder_model(apps, schema_editor):
+ model_cls = apps.get_model("product", "CollectionProduct")
+ new_values = model_cls.objects.values("id").annotate(
+ sort_order=Window(
+ expression=RowNumber(),
+ order_by=(F("sort_order").asc(nulls_last=True), "id"),
+ )
+ )
+
+ batch = [NewCollectionProductSortOrder(*row.values()) for row in new_values]
+ model_cls.objects.bulk_update(batch, ["sort_order"])
+
+ return reorder_model
+
+
+PRODUCT_TYPE_UNIQUE_SLUGS = [
+ migrations.RunPython(ensure_attribute_slugs_are_unique_or_fix)
+]
+
+ATTRIBUTE_MULTIPLE_VALUES = [
+ migrations.RunPython(migrate_attributes_to_list("Product")),
+ migrations.RunPython(migrate_attributes_to_list("ProductVariant")),
+]
+
+M2M_UNIQUE_TOGETHER = [migrations.RunPython(remove_duplicates_products_in_collections)]
+
+SORTING_NULLABLE_LOGIC = [
+ migrations.RunPython(ensure_model_is_ordered("AttributeValue")),
+ migrations.RunPython(ensure_model_is_ordered("CollectionProduct")),
+ migrations.RunPython(ensure_model_is_ordered("ProductImage")),
+]
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [("product", "0101_auto_20190719_0839")]
+
+ operations = (
+ PRODUCT_TYPE_UNIQUE_SLUGS
+ + ATTRIBUTE_MULTIPLE_VALUES
+ + M2M_UNIQUE_TOGETHER
+ + SORTING_NULLABLE_LOGIC
+ )
diff --git a/saleor/product/migrations/0102_unique_slug_attributes.py b/saleor/product/migrations/0102_unique_slug_attributes.py
deleted file mode 100644
index 8abeeb1ea7..0000000000
--- a/saleor/product/migrations/0102_unique_slug_attributes.py
+++ /dev/null
@@ -1,29 +0,0 @@
-# Generated by Django 2.2.2 on 2019-06-11 14:52
-
-from django.db import migrations, models
-from django.db.models import Count
-
-
-def ensure_attribute_slugs_are_unique_or_fix(apps, schema_editor):
- Attribute = apps.get_model("product", "Attribute") # noqa
- non_unique_slugs = (
- Attribute.objects.values_list("slug", flat=True)
- .annotate(slug_count=Count("slug"))
- .filter(slug_count__gt=1)
- )
- non_unique_attrs = Attribute.objects.filter(slug__in=list(non_unique_slugs))
- for suffix, attr in enumerate(non_unique_attrs):
- attr.slug += f"__{suffix}"
- attr.save(update_fields=["slug"])
-
-
-class Migration(migrations.Migration):
-
- dependencies = [("product", "0101_auto_20190719_0839")]
-
- operations = [
- migrations.RunPython(ensure_attribute_slugs_are_unique_or_fix),
- migrations.AlterField(
- model_name="attribute", name="slug", field=models.SlugField(unique=True)
- ),
- ]
diff --git a/saleor/product/migrations/0103_attribute_available_in_grid.py b/saleor/product/migrations/0103_attribute_available_in_grid.py
deleted file mode 100644
index 7065dfa1bc..0000000000
--- a/saleor/product/migrations/0103_attribute_available_in_grid.py
+++ /dev/null
@@ -1,16 +0,0 @@
-# Generated by Django 2.2.3 on 2019-07-19 13:43
-
-from django.db import migrations, models
-
-
-class Migration(migrations.Migration):
-
- dependencies = [("product", "0102_unique_slug_attributes")]
-
- operations = [
- migrations.AddField(
- model_name="attribute",
- name="available_in_grid",
- field=models.BooleanField(blank=True, default=True),
- )
- ]
diff --git a/saleor/product/migrations/0103_migrate_attrs_to_m2m.py b/saleor/product/migrations/0103_migrate_attrs_to_m2m.py
deleted file mode 100644
index 0a2f00ffb5..0000000000
--- a/saleor/product/migrations/0103_migrate_attrs_to_m2m.py
+++ /dev/null
@@ -1,183 +0,0 @@
-# Generated by Django 2.2.2 on 2019-06-12 08:15
-
-from django.db import migrations, models
-
-
-def migrate_fk_to_m2m(product_type_related_field):
- def make_migration(apps, schema):
- ProductType = apps.get_model("product", "ProductType")
-
- for product_type in ProductType.objects.all():
- m2m_field = getattr(product_type, product_type_related_field)
- attributes_to_migrate = getattr(
- product_type, f"{product_type_related_field}_old"
- )
- for attr in attributes_to_migrate.all():
- if product_type not in m2m_field.all():
- m2m_field.add(attr)
-
- return make_migration
-
-
-class Migration(migrations.Migration):
-
- dependencies = [("product", "0103_attribute_available_in_grid")]
-
- operations = [
- migrations.AddField(
- model_name="attribute",
- name="is_variant_only",
- field=models.BooleanField(default=False, blank=True),
- ),
- # Rename the foreign keys to backup them before overriding and processing them
- migrations.RenameField(
- model_name="attribute", old_name="product_type", new_name="product_type_old"
- ),
- migrations.RenameField(
- model_name="attribute",
- old_name="product_variant_type",
- new_name="product_variant_type_old",
- ),
- # Rename related names of foreign keys
- migrations.AlterField(
- model_name="attribute",
- name="product_type_old",
- field=models.ForeignKey(
- blank=True,
- null=True,
- on_delete=models.deletion.CASCADE,
- related_name="product_attributes_old",
- to="product.ProductType",
- ),
- ),
- migrations.AlterField(
- model_name="attribute",
- name="product_variant_type_old",
- field=models.ForeignKey(
- blank=True,
- null=True,
- on_delete=models.deletion.CASCADE,
- related_name="variant_attributes_old",
- to="product.ProductType",
- ),
- ),
- # Add the M2M new fields
- migrations.CreateModel(
- name="AttributeProduct",
- fields=[
- (
- "id",
- models.AutoField(
- auto_created=True,
- primary_key=True,
- serialize=False,
- verbose_name="ID",
- ),
- ),
- (
- "attribute",
- models.ForeignKey(
- on_delete=models.deletion.CASCADE,
- related_name="attributeproduct",
- to="product.Attribute",
- ),
- ),
- (
- "product_type",
- models.ForeignKey(
- on_delete=models.deletion.CASCADE,
- related_name="attributeproduct",
- to="product.ProductType",
- ),
- ),
- ],
- options={"abstract": False},
- ),
- migrations.CreateModel(
- name="AttributeVariant",
- fields=[
- (
- "id",
- models.AutoField(
- auto_created=True,
- primary_key=True,
- serialize=False,
- verbose_name="ID",
- ),
- ),
- (
- "attribute",
- models.ForeignKey(
- on_delete=models.deletion.CASCADE,
- related_name="attributevariant",
- to="product.Attribute",
- ),
- ),
- (
- "product_type",
- models.ForeignKey(
- on_delete=models.deletion.CASCADE,
- related_name="attributevariant",
- to="product.ProductType",
- ),
- ),
- ],
- options={"abstract": False},
- ),
- migrations.AddField(
- model_name="attribute",
- name="product_types",
- field=models.ManyToManyField(
- blank=True,
- related_name="product_attributes",
- through="product.AttributeProduct",
- to="product.ProductType",
- ),
- ),
- migrations.AddField(
- model_name="attribute",
- name="product_variant_types",
- field=models.ManyToManyField(
- blank=True,
- related_name="variant_attributes",
- through="product.AttributeVariant",
- to="product.ProductType",
- ),
- ),
- # Migrate the foreign keys into M2M
- migrations.RunPython(migrate_fk_to_m2m("product_attributes")),
- migrations.RunPython(migrate_fk_to_m2m("variant_attributes")),
- # Remove the migrated foreign keys
- migrations.RemoveField(model_name="attribute", name="product_variant_type_old"),
- migrations.RemoveField(model_name="attribute", name="product_type_old"),
- # whether the attribute is visible in storefront
- migrations.AddField(
- model_name="attribute",
- name="visible_in_storefront",
- field=models.BooleanField(default=True, blank=True),
- ),
- migrations.AddField(
- model_name="attribute",
- name="filterable_in_dashboard",
- field=models.BooleanField(default=True, blank=True),
- ),
- migrations.AddField(
- model_name="attribute",
- name="filterable_in_storefront",
- field=models.BooleanField(default=True, blank=True),
- ),
- migrations.AddField(
- model_name="attribute",
- name="value_required",
- field=models.BooleanField(default=False, blank=True),
- ),
- migrations.AlterModelOptions(
- name="attribute",
- options={"ordering": ("storefront_search_position", "slug")},
- ),
- migrations.AddField(
- model_name="attribute",
- name="storefront_search_position",
- field=models.IntegerField(default=0, blank=True),
- ),
- ]
diff --git a/saleor/product/migrations/0103_schema_data_enterprise_grade_attributes.py b/saleor/product/migrations/0103_schema_data_enterprise_grade_attributes.py
new file mode 100644
index 0000000000..5ba2e09eff
--- /dev/null
+++ b/saleor/product/migrations/0103_schema_data_enterprise_grade_attributes.py
@@ -0,0 +1,271 @@
+from django.db import migrations, models
+
+from saleor.core.fields import FilterableJSONBField
+from saleor.product.models import validate_attribute_json
+
+
+def migrate_fk_to_m2m(product_type_related_field):
+ """Migrate product types' foreign key to a M2M relation."""
+
+ def make_migration(apps, schema):
+ ProductType = apps.get_model("product", "ProductType")
+
+ for product_type in ProductType.objects.all():
+ m2m_field = getattr(product_type, product_type_related_field)
+ attributes_to_migrate = getattr(
+ product_type, f"{product_type_related_field}_old"
+ )
+ for attr in attributes_to_migrate.all():
+ if product_type not in m2m_field.all():
+ m2m_field.add(attr)
+
+ return make_migration
+
+
+PRODUCT_TYPE_UNIQUE_SLUGS = [
+ migrations.AlterField(
+ model_name="attribute", name="slug", field=models.SlugField(unique=True)
+ )
+]
+
+ATTRIBUTE_NEW_FIELDS = [
+ migrations.AddField(
+ model_name="attribute",
+ name="input_type",
+ field=models.CharField(
+ choices=[("dropdown", "Dropdown"), ("multiselect", "Multi Select")],
+ default="dropdown",
+ max_length=50,
+ ),
+ ),
+ migrations.AlterField(
+ model_name="product",
+ name="attributes",
+ field=FilterableJSONBField(
+ blank=True, default=dict, validators=[validate_attribute_json]
+ ),
+ ),
+ migrations.AlterField(
+ model_name="productvariant",
+ name="attributes",
+ field=FilterableJSONBField(
+ blank=True, default=dict, validators=[validate_attribute_json]
+ ),
+ ),
+ migrations.AddField(
+ model_name="attribute",
+ name="available_in_grid",
+ field=models.BooleanField(blank=True, default=True),
+ ),
+ migrations.AddField(
+ model_name="attribute",
+ name="visible_in_storefront",
+ field=models.BooleanField(default=True, blank=True),
+ ),
+ migrations.AddField(
+ model_name="attribute",
+ name="filterable_in_dashboard",
+ field=models.BooleanField(default=True, blank=True),
+ ),
+ migrations.AddField(
+ model_name="attribute",
+ name="filterable_in_storefront",
+ field=models.BooleanField(default=True, blank=True),
+ ),
+ migrations.AddField(
+ model_name="attribute",
+ name="value_required",
+ field=models.BooleanField(default=False, blank=True),
+ ),
+ migrations.AddField(
+ model_name="attribute",
+ name="storefront_search_position",
+ field=models.IntegerField(default=0, blank=True),
+ ),
+ migrations.AlterModelOptions(
+ name="attribute", options={"ordering": ("storefront_search_position", "slug")}
+ ),
+]
+
+PRODUCT_TYPE_NEW_RELATION = [
+ migrations.AddField(
+ model_name="attribute",
+ name="is_variant_only",
+ field=models.BooleanField(default=False, blank=True),
+ ),
+ # Rename the foreign keys to backup them before overriding and processing them
+ migrations.RenameField(
+ model_name="attribute", old_name="product_type", new_name="product_type_old"
+ ),
+ migrations.RenameField(
+ model_name="attribute",
+ old_name="product_variant_type",
+ new_name="product_variant_type_old",
+ ),
+ # Rename related names of foreign keys
+ migrations.AlterField(
+ model_name="attribute",
+ name="product_type_old",
+ field=models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=models.deletion.CASCADE,
+ related_name="product_attributes_old",
+ to="product.ProductType",
+ ),
+ ),
+ migrations.AlterField(
+ model_name="attribute",
+ name="product_variant_type_old",
+ field=models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=models.deletion.CASCADE,
+ related_name="variant_attributes_old",
+ to="product.ProductType",
+ ),
+ ),
+ # Add the M2M new fields
+ migrations.CreateModel(
+ name="AttributeProduct",
+ fields=[
+ (
+ "id",
+ models.AutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ (
+ "attribute",
+ models.ForeignKey(
+ on_delete=models.deletion.CASCADE,
+ related_name="attributeproduct",
+ to="product.Attribute",
+ ),
+ ),
+ (
+ "product_type",
+ models.ForeignKey(
+ on_delete=models.deletion.CASCADE,
+ related_name="attributeproduct",
+ to="product.ProductType",
+ ),
+ ),
+ (
+ "sort_order",
+ models.IntegerField(db_index=True, editable=False, null=True),
+ ),
+ ],
+ options={"abstract": False},
+ ),
+ migrations.CreateModel(
+ name="AttributeVariant",
+ fields=[
+ (
+ "id",
+ models.AutoField(
+ auto_created=True,
+ primary_key=True,
+ serialize=False,
+ verbose_name="ID",
+ ),
+ ),
+ (
+ "attribute",
+ models.ForeignKey(
+ on_delete=models.deletion.CASCADE,
+ related_name="attributevariant",
+ to="product.Attribute",
+ ),
+ ),
+ (
+ "product_type",
+ models.ForeignKey(
+ on_delete=models.deletion.CASCADE,
+ related_name="attributevariant",
+ to="product.ProductType",
+ ),
+ ),
+ (
+ "sort_order",
+ models.IntegerField(db_index=True, editable=False, null=True),
+ ),
+ ],
+ options={"abstract": False},
+ ),
+ migrations.AddField(
+ model_name="attribute",
+ name="product_types",
+ field=models.ManyToManyField(
+ blank=True,
+ related_name="product_attributes",
+ through="product.AttributeProduct",
+ to="product.ProductType",
+ ),
+ ),
+ migrations.AddField(
+ model_name="attribute",
+ name="product_variant_types",
+ field=models.ManyToManyField(
+ blank=True,
+ related_name="variant_attributes",
+ through="product.AttributeVariant",
+ to="product.ProductType",
+ ),
+ ),
+ # Migrate the foreign keys into M2M
+ migrations.RunPython(migrate_fk_to_m2m("product_attributes")),
+ migrations.RunPython(migrate_fk_to_m2m("variant_attributes")),
+ # Remove the migrated foreign keys
+ migrations.RemoveField(model_name="attribute", name="product_variant_type_old"),
+ migrations.RemoveField(model_name="attribute", name="product_type_old"),
+]
+
+SORTING_NULLABLE_LOGIC = [
+ migrations.AlterField(
+ model_name="attributevalue",
+ name="sort_order",
+ field=models.IntegerField(db_index=True, editable=False, null=True),
+ ),
+ migrations.AlterField(
+ model_name="collectionproduct",
+ name="sort_order",
+ field=models.IntegerField(db_index=True, editable=False, null=True),
+ ),
+ migrations.AlterField(
+ model_name="productimage",
+ name="sort_order",
+ field=models.IntegerField(db_index=True, editable=False, null=True),
+ ),
+ migrations.AlterModelOptions(
+ name="attributevalue", options={"ordering": ("sort_order", "id")}
+ ),
+]
+
+M2M_UNIQUE_TOGETHER = [
+ migrations.AlterUniqueTogether(
+ name="attributeproduct", unique_together={("attribute", "product_type")}
+ ),
+ migrations.AlterUniqueTogether(
+ name="attributevariant", unique_together={("attribute", "product_type")}
+ ),
+ migrations.AlterUniqueTogether(
+ name="collectionproduct", unique_together={("collection", "product")}
+ ),
+]
+
+
+class Migration(migrations.Migration):
+
+ dependencies = [("product", "0102_migrate_data_enterprise_grade_attributes")]
+
+ operations = (
+ PRODUCT_TYPE_UNIQUE_SLUGS
+ + ATTRIBUTE_NEW_FIELDS
+ + PRODUCT_TYPE_NEW_RELATION
+ + SORTING_NULLABLE_LOGIC
+ + M2M_UNIQUE_TOGETHER
+ )
diff --git a/saleor/product/migrations/0104_attribute_input_type_multiple_values.py b/saleor/product/migrations/0104_attribute_input_type_multiple_values.py
deleted file mode 100644
index 9713c830e5..0000000000
--- a/saleor/product/migrations/0104_attribute_input_type_multiple_values.py
+++ /dev/null
@@ -1,58 +0,0 @@
-# Generated by Django 2.2.2 on 2019-06-10 10:25
-
-from django.db import migrations, models
-
-from saleor.core.fields import FilterableJSONBField
-from saleor.product.models import validate_attribute_json
-
-
-def migrate_attributes_to_list(model_name):
- def make_migration(apps, schema):
- Model = apps.get_model("product", model_name)
-
- for instance in Model.objects.all():
- new_attributes = {}
-
- for k, v in instance.attributes.items():
- if not isinstance(v, list):
- new_attributes[k] = [v]
- else:
- new_attributes[k] = v
-
- instance.attributes = new_attributes
- instance.save(update_fields=["attributes"])
-
- return make_migration
-
-
-class Migration(migrations.Migration):
-
- dependencies = [("product", "0103_migrate_attrs_to_m2m")]
-
- operations = [
- migrations.AddField(
- model_name="attribute",
- name="input_type",
- field=models.CharField(
- choices=[("dropdown", "Dropdown"), ("multiselect", "Multi Select")],
- default="dropdown",
- max_length=50,
- ),
- ),
- migrations.AlterField(
- model_name="product",
- name="attributes",
- field=FilterableJSONBField(
- blank=True, default=dict, validators=[validate_attribute_json]
- ),
- ),
- migrations.AlterField(
- model_name="productvariant",
- name="attributes",
- field=FilterableJSONBField(
- blank=True, default=dict, validators=[validate_attribute_json]
- ),
- ),
- migrations.RunPython(migrate_attributes_to_list("Product")),
- migrations.RunPython(migrate_attributes_to_list("ProductVariant")),
- ]
diff --git a/saleor/product/migrations/0105_remove_dups.py b/saleor/product/migrations/0105_remove_dups.py
deleted file mode 100644
index f192a49f70..0000000000
--- a/saleor/product/migrations/0105_remove_dups.py
+++ /dev/null
@@ -1,58 +0,0 @@
-# Generated by Django 2.2.3 on 2019-07-24 07:56
-
-from django.db import migrations
-from django.db.models import Count
-
-
-def remove_duplicates(apps, schema_editor):
- """Removes any duplicated M2M, and keep only one of them.
-
- First we select the duplicates, by grouping them and counting them:
-
- SELECT
- collection_id, product_id, COUNT(*)
- FROM
- public.product_collectionproduct
- GROUP BY
- collection_id, product_id
- HAVING
- COUNT(*) > 1
-
- Then we retrieve all of them except one (LIMIT = `duplicate_count - 1`).
-
- Once we have them, we delete each of them manually (cannot directly delete by using
- LIMIT).
- """
-
- CollectionProduct = apps.get_model("product", "CollectionProduct")
-
- duplicates = (
- CollectionProduct.objects.values("collection_id", "product_id")
- .annotate(duplicate_count=Count("*"))
- .filter(duplicate_count__gt=1)
- )
-
- for duplicate in duplicates:
- dup_count = duplicate.pop("duplicate_count")
- delete_limit = dup_count - 1
- entries_to_delete = CollectionProduct.objects.filter(**duplicate)[:delete_limit]
- for entry in entries_to_delete:
- entry.delete()
-
-
-class Migration(migrations.Migration):
-
- dependencies = [("product", "0104_attribute_input_type_multiple_values")]
-
- operations = [
- migrations.RunPython(remove_duplicates),
- migrations.AlterUniqueTogether(
- name="attributeproduct", unique_together={("attribute", "product_type")}
- ),
- migrations.AlterUniqueTogether(
- name="attributevariant", unique_together={("attribute", "product_type")}
- ),
- migrations.AlterUniqueTogether(
- name="collectionproduct", unique_together={("collection", "product")}
- ),
- ]
diff --git a/saleor/product/migrations/0106_nullable_sort_logic.py b/saleor/product/migrations/0106_nullable_sort_logic.py
deleted file mode 100644
index 7e49db3488..0000000000
--- a/saleor/product/migrations/0106_nullable_sort_logic.py
+++ /dev/null
@@ -1,63 +0,0 @@
-# Generated by Django 2.2.3 on 2019-07-25 13:11
-
-from dataclasses import dataclass
-
-from django.db import migrations, models
-from django.db.models import F, Window
-from django.db.models.functions import RowNumber
-
-
-@dataclass(frozen=True)
-class NewCollectionProductSortOrder:
- pk: int
- sort_order: int
-
-
-def reorder_collection_products(apps, schema_editor):
- CollectionProduct = apps.get_model("product", "CollectionProduct")
- new_values = CollectionProduct.objects.values("id").annotate(
- sort_order=Window(
- expression=RowNumber(),
- order_by=(F("sort_order").asc(nulls_last=True), "id"),
- )
- )
-
- batch = [NewCollectionProductSortOrder(*row.values()) for row in new_values]
- CollectionProduct.objects.bulk_update(batch, ["sort_order"])
-
-
-class Migration(migrations.Migration):
-
- dependencies = [("product", "0105_remove_dups")]
-
- operations = [
- migrations.RunPython(reorder_collection_products),
- migrations.AddField(
- model_name="attributeproduct",
- name="sort_order",
- field=models.IntegerField(db_index=True, editable=False, null=True),
- ),
- migrations.AddField(
- model_name="attributevariant",
- name="sort_order",
- field=models.IntegerField(db_index=True, editable=False, null=True),
- ),
- migrations.AlterField(
- model_name="attributevalue",
- name="sort_order",
- field=models.IntegerField(db_index=True, editable=False, null=True),
- ),
- migrations.AlterField(
- model_name="collectionproduct",
- name="sort_order",
- field=models.IntegerField(db_index=True, editable=False, null=True),
- ),
- migrations.AlterField(
- model_name="productimage",
- name="sort_order",
- field=models.IntegerField(db_index=True, editable=False, null=True),
- ),
- migrations.AlterModelOptions(
- name="attributevalue", options={"ordering": ("sort_order", "id")}
- ),
- ]