Skip to content

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

Add a new field on AssignedVariantAttributeValue to store relation to Variant model (#18427)

Iga Karbowiak8c015055427d
diff --git a/saleor/attribute/migrations/0034_assignedpageattributevalue_page_data_migration.py b/saleor/attribute/migrations/0034_assignedpageattributevalue_page_data_migration.py
index a5652814f3..7465613498 100644
--- a/saleor/attribute/migrations/0034_assignedpageattributevalue_page_data_migration.py
+++ b/saleor/attribute/migrations/0034_assignedpageattributevalue_page_data_migration.py
@@ -34,7 +34,7 @@ def update_page_assignment():
SELECT av.id
FROM attribute_assignedpageattributevalue AS av
WHERE av.page_id IS NULL
- ORDER BY av.id DESC
+ ORDER BY av.sort_order, av.id DESC
LIMIT %s
FOR UPDATE
)
diff --git a/saleor/attribute/migrations/0036_assignedproductattributevalue_product_data_migration.py b/saleor/attribute/migrations/0036_assignedproductattributevalue_product_data_migration.py
index 7330d86b0c..9ac8ff3c26 100644
--- a/saleor/attribute/migrations/0036_assignedproductattributevalue_product_data_migration.py
+++ b/saleor/attribute/migrations/0036_assignedproductattributevalue_product_data_migration.py
@@ -37,7 +37,7 @@ def update_product_assignment():
WHERE id IN (
SELECT ID FROM attribute_assignedproductattributevalue
WHERE product_id IS NULL
- ORDER BY ID DESC
+ ORDER BY SORT_ORDER, ID DESC
FOR UPDATE
LIMIT %s
);
diff --git a/saleor/attribute/migrations/0055_assignedvariantattributevalue_variant.py b/saleor/attribute/migrations/0055_assignedvariantattributevalue_variant.py
new file mode 100644
index 0000000000..603e698608
--- /dev/null
+++ b/saleor/attribute/migrations/0055_assignedvariantattributevalue_variant.py
@@ -0,0 +1,68 @@
+# Generated by Django 4.2.18 on 2025-02-13 14:14
+
+import django.db.models.deletion
+from django.db import connection, migrations, models, transaction
+
+BATCH_SIZE = 500
+
+
+def update_product_variant_assignment():
+ """Assign variant_id to a new field on assignedproductattributevalue.
+
+ Take the values from attribute_assignedvariantattribute to variant_id and copy it over
+ to attribute_assignedvariantattributevalue variant_id.
+ """
+ with transaction.atomic():
+ with connection.cursor() as cursor:
+ cursor.execute(
+ """
+ UPDATE attribute_assignedvariantattributevalue
+ SET variant_id = (
+ SELECT variant_id
+ FROM attribute_assignedvariantattribute
+ WHERE attribute_assignedvariantattributevalue.assignment_id = attribute_assignedvariantattribute.id
+ )
+ WHERE id IN (
+ SELECT ID FROM attribute_assignedvariantattributevalue
+ WHERE VARIANT_ID IS NULL
+ ORDER BY SORT_ORDER, ID DESC
+ FOR UPDATE
+ LIMIT %s
+ );
+ """,
+ [BATCH_SIZE],
+ )
+
+
+def data_migration(apps, _schema_editor):
+ AssignedVariantAttributeValue = apps.get_model(
+ "attribute", "AssignedVariantAttributeValue"
+ )
+ while (
+ AssignedVariantAttributeValue.objects.filter(variant__isnull=True)
+ .values_list("pk", flat=True)
+ .exists()
+ ):
+ update_product_variant_assignment()
+
+
+class Migration(migrations.Migration):
+ dependencies = [
+ ("product", "0197_productvariantchannellisting_prior_price_amount"),
+ ("attribute", "0054_attribute_reference_page_and_product_types"),
+ ]
+
+ operations = [
+ migrations.AddField(
+ model_name="assignedvariantattributevalue",
+ name="variant",
+ field=models.ForeignKey(
+ blank=True,
+ null=True,
+ on_delete=django.db.models.deletion.CASCADE,
+ related_name="attributevalues",
+ to="product.productvariant",
+ ),
+ ),
+ migrations.RunPython(data_migration, migrations.RunPython.noop),
+ ]
diff --git a/saleor/attribute/models/product_variant.py b/saleor/attribute/models/product_variant.py
index cc2f278ead..7d2da72e01 100644
--- a/saleor/attribute/models/product_variant.py
+++ b/saleor/attribute/models/product_variant.py
@@ -16,6 +16,13 @@ class AssignedVariantAttributeValue(SortableModel):
on_delete=models.CASCADE,
related_name="variantvalueassignment",
)
+ variant = models.ForeignKey(
+ ProductVariant,
+ related_name="attributevalues",
+ on_delete=models.CASCADE,
+ null=True,
+ blank=True,
+ )
class Meta:
unique_together = (("value", "assignment"),)
diff --git a/saleor/attribute/tests/test_utils.py b/saleor/attribute/tests/test_utils.py
index 9f830f7415..c510304615 100644
--- a/saleor/attribute/tests/test_utils.py
+++ b/saleor/attribute/tests/test_utils.py
@@ -16,38 +16,6 @@ from .model_helpers import (
)
-def attribute_1():
- attr = Attribute.objects.create(
- slug="attribute-1",
- name="Attribute 1",
- input_type=AttributeInputType.DROPDOWN,
- type=AttributeType.PRODUCT_TYPE,
- )
- AttributeValue.objects.create(
- attribute=attr,
- name="Value 1",
- slug="value-1",
- )
- return attr
-
-
-def attribute_2():
- attr = Attribute.objects.create(
- slug="attribute-2",
- name="Attribute 2",
- input_type=AttributeInputType.DROPDOWN,
- type=AttributeType.PRODUCT_TYPE,
- )
- AttributeValue.objects.create(
- attribute=attr,
- name="Value 1",
- slug="value-1",
- )
- return attr
-
-
def test_associate_attribute_to_non_product_instance(color_attribute):
instance = ProductType()
attribute = color_attribute
@@ -249,11 +217,34 @@ def test_associate_attribute_to_instance_duplicated_values(
}
-def test_validate_attribute_owns_values(attribute_1, attribute_2):
+def test_validate_attribute_owns_values():
+ attribute_1 = Attribute.objects.create(
+ slug="attribute-1",
+ name="Attribute 1",
+ input_type=AttributeInputType.DROPDOWN,
+ type=AttributeType.PRODUCT_TYPE,
+ )
+ value_1 = AttributeValue.objects.create(
+ attribute=attribute_1,
+ name="Value 1",
+ slug="value-1",
+ )
+
+ attribute_2 = Attribute.objects.create(
+ slug="attribute-2",
+ name="Attribute 2",
+ input_type=AttributeInputType.DROPDOWN,
+ type=AttributeType.PRODUCT_TYPE,
+ )
+ value_2 = AttributeValue.objects.create(
+ attribute=attribute_2,
+ name="Value 1",
+ slug="value-1",
+ )
# given
attr_val_map = {
- attribute_1.id: [attribute_1.values.first()],
- attribute_2.id: [attribute_2.values.first()],
+ attribute_1.id: [value_1],
+ attribute_2.id: [value_2],
}
# when
@@ -261,6 +252,36 @@ def test_validate_attribute_owns_values(attribute_1, attribute_2):
# then
assert attr_val_map == {
- attribute_1.id: [attribute_1.values.first()],
- attribute_2.id: [attribute_2.values.first()],
+ attribute_1.id: [value_1],
+ attribute_2.id: [value_2],
}
+
+
+def test_associate_attribute_to_variant_copies_data_over_to_new_field(
+ variant, attribute_value_generator
+):
+ """Ensure data is double writed.
+
+ Part of implementation of the #12881 issue. We need to check that the
+ value of AssignedVariantAttribute.variant is copied over to
+ AssignedVariantAttributeValue.variant.
+ """
+ attribute = variant.product.product_type.variant_attributes.first()
+ attribute_value_generator(
+ attribute=attribute,
+ slug="attr-value2",
+ )
+ values = attribute.values.all()
+
+ # Assign new values
+ associate_attribute_values_to_instance(
+ variant,
+ {attribute.id: values},
+ )
+
+ # Ensure the new assignment was created
+ assert variant.attributevalues.count() == 2
+ assert list(variant.attributevalues.values_list("value_id", "variant_id")) == [
+ (values[0].pk, variant.id),
+ (values[1].pk, variant.id),
+ ]
diff --git a/saleor/attribute/utils.py b/saleor/attribute/utils.py
index e3d3d90362..977977bf3b 100644
--- a/saleor/attribute/utils.py
+++ b/saleor/attribute/utils.py
@@ -1,6 +1,6 @@
from collections import defaultdict
-from functools import reduce
+from django.conf import settings
from django.db.models import Exists, OuterRef, Q
from ..page.models import Page
@@ -10,8 +10,6 @@ from .models import (
AssignedProductAttributeValue,
AssignedVariantAttribute,
AssignedVariantAttributeValue,
- AttributePage,
- AttributeProduct,
AttributeValue,
AttributeVariant,
)
@@ -21,16 +19,14 @@ T_INSTANCE = Product | ProductVariant | Page
instance_to_function_variables_mapping = {
"Product": (
- AttributeProduct,
AssignedProductAttributeValue,
"product",
),
"ProductVariant": (
- AttributeVariant,
AssignedVariantAttributeValue,
"variant",
),
- "Page": (AttributePage, AssignedPageAttributeValue, "page"),
+ "Page": (AssignedPageAttributeValue, "page"),
}
@@ -56,16 +52,15 @@ def validate_attribute_owns_values(attr_val_map: dict[int, list]) -> None:
values_map = defaultdict(set)
slug_value_to_value_map = {}
- # we need to fetch the proper values which attribute ids and value slug matches
- lookup = reduce(
- lambda acc, val_map_item: acc
- | Q(
- attribute_id=val_map_item[0], slug__in=[val.slug for val in val_map_item[1]]
- ),
- attr_val_map.items(),
- Q(),
- )
- values = AttributeValue.objects.filter(lookup)
+ # prepare a lookup with all attributes and their values to get them from the db
+ lookup = Q()
+ for attribute_id, values in attr_val_map.items():
+ value_slugs = [value.slug for value in values]
+ lookup |= Q(attribute_id=attribute_id, slug__in=value_slugs)
+
+ values = AttributeValue.objects.using(
+ settings.DATABASE_CONNECTION_REPLICA_NAME
+ ).filter(lookup)
for value in values:
attr_id = value.attribute_id
@@ -91,9 +86,7 @@ def _associate_attribute_to_instance(
if not variables:
raise AssertionError(f"{instance_type} is unsupported")
-
(
- instance_attribute_model,
value_model,
instance_field_name,
) = variables
@@ -105,7 +98,8 @@ def _associate_attribute_to_instance(
"attribute_id__in": list(attr_val_map.keys()),
"product_type_id": prod_type_id,
}
- instance_attrs_ids = instance_attribute_model.objects.filter( # type: ignore[attr-defined]
+
+ instance_attrs_ids = AttributeVariant.objects.filter(
**attribute_filter
).values_list("pk", flat=True)
@@ -122,9 +116,7 @@ def _associate_attribute_to_instance(
)
if isinstance(instance, ProductVariant):
- _order_variant_assigned_attr_values(
- values_order_map, assignments, attr_val_map, AssignedVariantAttributeValue
- )
+ _order_variant_assigned_attr_values(values_order_map, assignments, attr_val_map)
else:
_order_assigned_attr_values(
values_order_map, attr_val_map, value_model, instance_field_name, instance
@@ -197,6 +189,7 @@ def _overwrite_values(
# unique_together is set for product + value on AssignedProductAttributeValue
values_order_map = defaultdict(list)
assigned_attr_values_instances = []
+
for attr_id, values in attr_val_map.items():
assignment = assignment_attr_map.get(attr_id)
@@ -249,13 +242,23 @@ def _order_assigned_attr_values(
def _order_variant_assigned_attr_values(
- values_order_map, assignments, attr_val_map, assignment_model
+ values_order_map,
+ assignments,
+ attr_val_map,
) -> None:
- assigned_attrs_values = assignment_model.objects.filter(
+ assigned_attrs_values = AssignedVariantAttributeValue.objects.filter(
assignment_id__in=(a.pk for a in assignments),
value_id__in=(v.pk for values in attr_val_map.values() for v in values),
)
for value in assigned_attrs_values:
value.sort_order = values_order_map[value.assignment_id].index(value.value_id)
- assignment_model.objects.bulk_update(assigned_attrs_values, ["sort_order"])
+ # While migrating to a new structure we need to make sure we also
+ # copy the assigned variant to AssignedVariantAttributeValue
+ # where it will live after issue #12881 will be implemented
+ value.variant_id = value.assignment.variant_id
+
+ # Remove "variant" once the above double save is removed
+ AssignedVariantAttributeValue.objects.bulk_update(
+ assigned_attrs_values, ["sort_order", "variant"]
+ )