Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Introduce a partial data migration to copy over values to new field
Ania Warzecha1de6babf8f71
diff --git a/saleor/attribute/migrations/0030_assignedproductattributevalue_product.py b/saleor/attribute/migrations/0030_assignedproductattributevalue_product.pynew file mode 100644index 0000000000..d78b478490--- /dev/null+++ b/saleor/attribute/migrations/0030_assignedproductattributevalue_product.py@@ -0,0 +1,38 @@+# Generated by Django 3.2.20 on 2023-08-23 20:21++from django.db import migrations, models+import django.db.models.deletion+from django.db.models.signals import post_migrate+from django.apps import apps as registry++from .tasks.saleor3_16 import assign_products_to_attribute_values_task+++def enqueue_data_migration(apps, _schema_editor):+ def on_migrations_complete(sender=None, **kwargs):+ assign_products_to_attribute_values_task.delay()++ sender = registry.get_app_config("attribute")+ post_migrate.connect(on_migrations_complete, weak=False, sender=sender)+++class Migration(migrations.Migration):+ dependencies = [+ ("product", "0186_remove_product_charge_taxes"),+ ("attribute", "0029_alter_attribute_unit"),+ ]++ operations = [+ migrations.AddField(+ model_name="assignedproductattributevalue",+ name="product",+ field=models.ForeignKey(+ blank=True,+ null=True,+ on_delete=django.db.models.deletion.CASCADE,+ related_name="attributevalues",+ to="product.product",+ ),+ ),+ migrations.RunPython(enqueue_data_migration, migrations.RunPython.noop),+ ]diff --git a/saleor/attribute/migrations/tasks/saleor3_16.py b/saleor/attribute/migrations/tasks/saleor3_16.pynew file mode 100644index 0000000000..8b6a22a0c0--- /dev/null+++ b/saleor/attribute/migrations/tasks/saleor3_16.py@@ -0,0 +1,49 @@+from ....celeryconf import app+from ...models import AssignedProductAttributeValue++from django.db import connection++# batch size to make sure that task is completed in 1 second+# and we don't use too much memory+BATCH_SIZE = 1000+++def update_product_assignment():+ """Assign product_id to a new field on assignedproductattributevalue.++ Take the values from attribute_assignedproductattribute to product_id.+ The old field has already been deleted in Django State operations so we need+ to use raw SQL to get the value and copy the assignment from the old table.+ """+ with connection.cursor() as cursor:+ cursor.execute(+ """+ UPDATE attribute_assignedproductattributevalue+ SET product_id = (+ SELECT product_id+ FROM attribute_assignedproductattribute+ WHERE attribute_assignedproductattributevalue.assignment_id = attribute_assignedproductattribute.id+ )+ WHERE id IN (+ SELECT ID FROM attribute_assignedproductattributevalue+ ORDER BY ID DESC+ FOR UPDATE+ LIMIT %s+ );+ """, # noqa+ [BATCH_SIZE],+ )+++def assign_products_to_attribute_values_task():+ # Order events proceed from the newest to the oldest+ assigned_values = (+ AssignedProductAttributeValue.objects.filter(product__isnull=True)+ .values_list("pk", flat=True)+ .exists()+ )+ # If we found data, queue next execution of the task+ if assigned_values:+ update_product_assignment()+ assign_products_to_attribute_values_task.delay()diff --git a/saleor/attribute/models/product.py b/saleor/attribute/models/product.pyindex 655cac2317..bad26b3a08 100644--- a/saleor/attribute/models/product.py+++ b/saleor/attribute/models/product.py@@ -17,6 +17,14 @@ class AssignedProductAttributeValue(SortableModel):related_name="productvalueassignment",)+ product = models.ForeignKey(+ Product,+ related_name="attributevalues",+ on_delete=models.CASCADE,+ null=True,+ blank=True,+ )+class Meta:unique_together = (("value", "assignment"),)ordering = ("sort_order", "pk")diff --git a/saleor/attribute/tests/test_utils.py b/saleor/attribute/tests/test_utils.pyindex 5e8f6cdaa7..99e79f2cae 100644--- a/saleor/attribute/tests/test_utils.py+++ b/saleor/attribute/tests/test_utils.py@@ -71,7 +71,7 @@ def test_associate_attribute_to_product_instance_multiple_values(assert new_assignment.pk == old_assignment.pkassert new_assignment.values.count() == 2assert list(- new_assignment.productvalueassignment.values_list("value__pk", "sort_order")+ new_assignment.productvalueassignment.values_list("value_id", "sort_order")) == [(values[1].pk, 0), (values[0].pk, 1)]@@ -93,7 +93,7 @@ def test_associate_attribute_to_page_instance_multiple_values(page):assert new_assignment.pk == old_assignment.pkassert new_assignment.values.count() == 2assert list(- new_assignment.pagevalueassignment.values_list("value__pk", "sort_order")+ new_assignment.pagevalueassignment.values_list("value_id", "sort_order")) == [(values[1].pk, 0), (values[0].pk, 1)]@@ -116,5 +116,38 @@ def test_associate_attribute_to_variant_instance_multiple_values(# Ensure the new assignment was created and ordered correctlyassert new_assignment.values.count() == 2assert list(- new_assignment.variantvalueassignment.values_list("value__pk", "sort_order")+ new_assignment.variantvalueassignment.values_list("value_id", "sort_order")) == [(values[0].pk, 0), (values[1].pk, 1)]+++def test_associate_attribute_to_product_copies_data_over_to_new_field(+ product, attribute_value_generator+):+ """Ensure data is double writed.++ Part of implementation of the #12881 issue. We need to check that the+ value of AssignedProductAttribute.product is copied over to+ AssignedProductAttributeValue.product.+ """+ old_assignment = product.attributes.first()+ assert old_assignment is not None, "The product doesn't have attribute-values"+ assert old_assignment.values.count() == 1++ attribute = old_assignment.attribute+ attribute_value_generator(+ attribute=attribute,+ slug="attr-value2",+ )+ values = attribute.values.all()++ # Assign new values+ new_assignment = associate_attribute_values_to_instance(+ product, attribute, values[1], values[0]+ )++ # Ensure the new assignment was created+ assert new_assignment.pk == old_assignment.pk+ assert new_assignment.values.count() == 2+ assert list(+ new_assignment.variantvalueassignment.values_list("value_id", "product_id")+ ) == [(values[0].pk, product.id), (values[1].pk, product.id)]diff --git a/saleor/attribute/utils.py b/saleor/attribute/utils.pyindex 938268c250..08376c6164 100644--- a/saleor/attribute/utils.py+++ b/saleor/attribute/utils.py@@ -71,6 +71,10 @@ def _associate_attribute_to_instance(assignment, _ = AssignedProductAttribute.objects.get_or_create(product=instance, assignment=attribute_rel)+ # While migrating to a new structure we need to make sure we also+ # copy the assigned product to AssignedProductAttributeValue+ # where it will live after issue #12881 will be implemented+ assignment.productvalueassignment.update(product_id=instance.pk)elif isinstance(instance, ProductVariant):attribute_rel = instance.product.product_type.attributevariant.get(attribute_id=attribute_pk