Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add model and API changes to the Product - Attribute relation
Ania Warzecha461bcf4e8453
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 55cb2319df..3d87d3f491 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -43,6 +43,7 @@ All notable, unreleased changes to this project will be documented in this file.- Added validation for timestamp comparison #14025 by @ritanjandawn- Page -> Attributes refactor. The goal is to simplify the attribute models. The current attribute model relations are complex and really hard to understand. - #13621- `requirements.txt` and `requirements_dev.txt` were dropped in favor of only supporting `poetry` - #14611 by @patrys+- Change the Attribute - Product relation to decrease code complexity and make it easier to understand the relations - #13407 by @aniav# 3.17.0diff --git a/saleor/attribute/migrations/0038_remove_assignedproductattribute.py b/saleor/attribute/migrations/0038_remove_assignedproductattribute.pynew file mode 100644index 0000000000..f2a2e7c238--- /dev/null+++ b/saleor/attribute/migrations/0038_remove_assignedproductattribute.py@@ -0,0 +1,96 @@+# Generated by Django 3.2.20 on 2023-07-11 16:10++import django.db.models.deletion+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("attribute", "0037_remove_assignedpageattribute"),+ ]++ state_operations = [+ migrations.RemoveField(+ model_name="attributeproduct",+ name="assigned_products",+ ),+ migrations.RemoveField(+ model_name="assignedproductattributevalue",+ name="assignment",+ ),+ migrations.DeleteModel(+ name="AssignedProductAttribute",+ ),+ migrations.AlterUniqueTogether(+ name="assignedproductattributevalue",+ unique_together={("value", "product")},+ ),+ migrations.AlterField(+ model_name="assignedproductattributevalue",+ name="product",+ field=models.ForeignKey(+ db_index=False,+ on_delete=django.db.models.deletion.CASCADE,+ related_name="attributevalues",+ to="product.product",+ ),+ ),+ ]++ operations = [+ # Set FKs to allow null values before marking their models/fields deleted+ migrations.AlterField(+ model_name="assignedproductattributevalue",+ name="assignment",+ field=models.ForeignKey(+ on_delete=django.db.models.deletion.SET_NULL,+ related_name="productvalueassignment",+ to="attribute.AssignedProductAttribute",+ null=True,+ ),+ ),+ migrations.AlterField(+ model_name="assignedproductattribute",+ name="product",+ field=models.ForeignKey(+ on_delete=django.db.models.deletion.SET_NULL,+ related_name="attributes",+ to="product.Product",+ null=True,+ ),+ ),+ migrations.AlterField(+ model_name="assignedproductattribute",+ name="assignment",+ field=models.ForeignKey(+ on_delete=django.db.models.deletion.SET_NULL,+ related_name="productassignments",+ to="attribute.AttributeProduct",+ null=True,+ ),+ ),+ # Remove FK constraints so that the DB doesn't try to truncate the references+ migrations.RunSQL(+ """+ ALTER TABLE attribute_assignedproductattribute+ DROP CONSTRAINT IF EXISTS+ attribute_assignedpr_assignment_id_f65ddd91_fk_attribute;+++ ALTER TABLE attribute_assignedproductattribute+ DROP CONSTRAINT IF EXISTS+ attribute_assignedpr_product_id_c267932a_fk_product_p;+++ ALTER TABLE attribute_assignedproductattributevalue+ DROP CONSTRAINT IF EXISTS+ attribute_assignedpa_assignment_id_6863be0a_fk_attribute;++ ALTER TABLE attribute_assignedproductattributevalue+ DROP CONSTRAINT IF EXISTS+ attribute_assignedproduc_value_id_assignment_id_ad6f5a87_uniq;+ """,+ reverse_sql=migrations.RunSQL.noop,+ ),+ migrations.SeparateDatabaseAndState(state_operations=state_operations),+ ]diff --git a/saleor/attribute/models/__init__.py b/saleor/attribute/models/__init__.pyindex 7f6bd3cfee..950b88a1c2 100644--- a/saleor/attribute/models/__init__.py+++ b/saleor/attribute/models/__init__.py@@ -5,11 +5,7 @@ from .base import (AttributeValueTranslation,)from .page import AssignedPageAttributeValue, AttributePage-from .product import (- AssignedProductAttribute,- AssignedProductAttributeValue,- AttributeProduct,-)+from .product import AssignedProductAttributeValue, AttributeProductfrom .product_variant import (AssignedVariantAttribute,AssignedVariantAttributeValue,@@ -23,7 +19,6 @@ __all__ = ["AttributeValueTranslation","AssignedPageAttributeValue","AttributePage",- "AssignedProductAttribute","AssignedProductAttributeValue","AttributeProduct","AssignedVariantAttribute",diff --git a/saleor/attribute/models/base.py b/saleor/attribute/models/base.pyindex 67e49a1a6f..b5acfce53b 100644--- a/saleor/attribute/models/base.py+++ b/saleor/attribute/models/base.py@@ -21,6 +21,8 @@ if TYPE_CHECKING:class BaseAssignedAttribute(models.Model):+ # TODO: stop using this class in new code+ # See: https://github.com/saleor/saleor/issues/12881class Meta:abstract = True@@ -312,9 +314,7 @@ class AttributeValueTranslation(Translation):elif assigned_product_attribute_value := (attribute_value.productvalueassignment.first()):- if product_id := (- assigned_product_attribute_value.assignment.product_id- ):+ if product_id := assigned_product_attribute_value.product_id:context["product_id"] = product_idelif attribute.type == AttributeType.PAGE_TYPE:if assigned_page_attribute_value := (diff --git a/saleor/attribute/models/product.py b/saleor/attribute/models/product.pyindex 4687219b82..03bf7948f0 100644--- a/saleor/attribute/models/product.py+++ b/saleor/attribute/models/product.py@@ -3,7 +3,7 @@ from django.db import modelsfrom ...core.models import SortableModelfrom ...product.models import Product, ProductType-from .base import AssociatedAttributeManager, AttributeValue, BaseAssignedAttribute+from .base import AssociatedAttributeManagerclass AssignedProductAttributeValue(SortableModel):@@ -12,50 +12,24 @@ class AssignedProductAttributeValue(SortableModel):on_delete=models.CASCADE,related_name="productvalueassignment",)- assignment = models.ForeignKey(- "AssignedProductAttribute",- on_delete=models.CASCADE,- related_name="productvalueassignment",- )-product = models.ForeignKey(Product,related_name="attributevalues",on_delete=models.CASCADE,- null=True,- blank=True,+ null=False,+ blank=False,db_index=False,)class Meta:- unique_together = (("value", "assignment"),)+ unique_together = (("value", "product"),)ordering = ("sort_order", "pk")indexes = [BTreeIndex(fields=["product"], name="assignedprodattrval_product_idx")]def get_ordering_queryset(self):- return self.assignment.productvalueassignment.all()---class AssignedProductAttribute(BaseAssignedAttribute):- """Associate a product type attribute and selected values to a given product."""-- product = models.ForeignKey(- Product, related_name="attributes", on_delete=models.CASCADE- )- assignment = models.ForeignKey(- "AttributeProduct", on_delete=models.CASCADE, related_name="productassignments"- )- values = models.ManyToManyField(- AttributeValue,- blank=True,- related_name="productassignments",- through=AssignedProductAttributeValue,- )-- class Meta:- unique_together = (("product", "assignment"),)+ return self.product.attributevalues.all()class AttributeProduct(SortableModel):@@ -65,13 +39,6 @@ class AttributeProduct(SortableModel):product_type = models.ForeignKey(ProductType, related_name="attributeproduct", on_delete=models.CASCADE)- assigned_products = models.ManyToManyField(- Product,- blank=True,- through=AssignedProductAttribute,- through_fields=("assignment", "product"),- related_name="attributesrelated",- )objects = AssociatedAttributeManager()diff --git a/saleor/attribute/tasks.py b/saleor/attribute/tasks.pyindex de2020bde7..6cd2781927 100644--- a/saleor/attribute/tasks.py+++ b/saleor/attribute/tasks.py@@ -26,6 +26,6 @@ def update_associated_products_search_vector(attribute_value_pk: int):Exists(instance.variantassignments.filter(variant_id=OuterRef("id"))))Product.objects.filter(- Q(Exists(instance.productassignments.filter(product_id=OuterRef("id"))))+ Q(Exists(instance.productvalueassignment.filter(product_id=OuterRef("id"))))| Q(Exists(variants.filter(product_id=OuterRef("id"))))).update(search_index_dirty=True)diff --git a/saleor/attribute/tests/model_helpers.py b/saleor/attribute/tests/model_helpers.pyindex cde5d51cec..1303c95408 100644--- a/saleor/attribute/tests/model_helpers.py+++ b/saleor/attribute/tests/model_helpers.py@@ -1,10 +1,13 @@from django.db.models.expressions import Exists, OuterReffrom ...page.models import Page+from ...product.models import Productfrom ..models import (AssignedPageAttributeValue,+ AssignedProductAttributeValue,Attribute,AttributePage,+ AttributeProduct,AttributeValue,)@@ -24,3 +27,36 @@ def get_page_attribute_values(page: Page, attribute: Attribute):return values.filter(Exists(assigned_values.filter(value_id=OuterRef("id"))),).order_by("pagevalueassignment__sort_order")+++def get_product_attributes(product: Product):+ """Get product attributes filtered by product_type.++ ProductType defines which attributes can be assigned to a product and+ we have to filter out the attributes on the instance by the ones attached to the+ product_type.+ """+ product_attributes = AttributeProduct.objects.filter(+ product_type_id=product.product_type_id+ )+ return Attribute.objects.filter(+ Exists(product_attributes.filter(attribute_id=OuterRef("id")))+ ).order_by("attributeproduct__sort_order")+++def get_product_attribute_values(product: Product, attribute: Attribute):+ """Get values assigned to a product.++ Note: this doesn't filter out attributes that might have been unassigned from the+ product type.+ """+ assigned_values = AssignedProductAttributeValue.objects.filter(+ product_id=product.pk+ )++ return AttributeValue.objects.filter(+ Exists(+ assigned_values.filter(value_id=OuterRef("id")),+ ),+ attribute_id=attribute.pk,+ ).order_by("productvalueassignment__sort_order")diff --git a/saleor/attribute/tests/test_utils.py b/saleor/attribute/tests/test_utils.pyindex 27dac2983a..06d758256f 100644--- a/saleor/attribute/tests/test_utils.py+++ b/saleor/attribute/tests/test_utils.py@@ -2,8 +2,15 @@ import pytestfrom ...attribute.models import AssignedPageAttributeValuefrom ...product.models import ProductType-from ..utils import associate_attribute_values_to_instance-from .model_helpers import get_page_attribute_values, get_page_attributes+from ..utils import (+ associate_attribute_values_to_instance,+)+from .model_helpers import (+ get_page_attribute_values,+ get_page_attributes,+ get_product_attribute_values,+ get_product_attributes,+)def test_associate_attribute_to_non_product_instance(color_attribute):@@ -32,29 +39,45 @@ def test_associate_attribute_to_product_instance_from_different_attribute(def test_associate_attribute_to_product_instance_without_values(product):"""Ensure clearing the values from a product is properly working."""- 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 = get_product_attributes(product).first()+ assert attribute is not None, "Product doesn't have attributes assigned"+ value_count = get_product_attribute_values(product, attribute).count()+ assert value_count == 1, "Product doesn't have attribute-values"# Clear the values- new_assignment = associate_attribute_values_to_instance(product, attribute)+ associate_attribute_values_to_instance(product, attribute)# Ensure the values were cleared and no new assignment entry was created- assert new_assignment.pk == old_assignment.pk- assert new_assignment.values.count() == 0+ assert get_product_attributes(product).count() == 1+ assert product.attributevalues.count() == 0+++def test_disassociate_attributes_from_instance(product):+ """Ensure clearing the values from a product is properly working."""+ attribute = get_product_attributes(product).first()+ assert attribute is not None, "Product doesn't have attributes assigned"+ value_count = get_product_attribute_values(product, attribute).count()+ assert value_count == 1, "Product doesn't have attribute-values"++ # This should clear the values+ associate_attribute_values_to_instance(product, attribute)++ # Check that the attribute still belongs to the product but doesn't have values+ attribute = get_product_attributes(product).first()+ assert attribute is not None, "Product doesn't have attributes assigned"+ value_count = get_product_attribute_values(product, attribute).count()+ assert value_count == 0, "Product has attribute-values assigned after removal"def test_associate_attribute_to_product_instance_multiple_values(product, attribute_value_generator):"""Ensure multiple values in proper order are assigned."""- 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 = get_product_attributes(product).first()+ assert attribute is not None, "Product doesn't have attributes assigned"+ value_count = get_product_attribute_values(product, attribute).count()+ assert value_count == 1, "Product doesn't have attribute-values"- attribute = old_assignment.attributeattribute_value_generator(attribute=attribute,slug="attr-value2",@@ -62,16 +85,14 @@ def test_associate_attribute_to_product_instance_multiple_values(values = attribute.values.all()# Assign new values- new_assignment = associate_attribute_values_to_instance(- product, attribute, values[1], values[0]- )+ associate_attribute_values_to_instance(product, attribute, values[1], values[0])# Ensure the new assignment was created and ordered correctly- assert new_assignment.pk == old_assignment.pk- assert new_assignment.values.count() == 2- assert list(- new_assignment.productvalueassignment.values_list("value_id", "sort_order")- ) == [(values[1].pk, 0), (values[0].pk, 1)]+ assert product.attributevalues.count() == 2+ assert list(product.attributevalues.values_list("value_id", "sort_order")) == [+ (values[1].pk, 0),+ (values[0].pk, 1),+ ]def test_associate_attribute_to_page_instance_multiple_values(page):@@ -135,12 +156,13 @@ def test_associate_attribute_to_product_copies_data_over_to_new_field(values = color_attribute.values.all()# Assign new values- new_assignment = associate_attribute_values_to_instance(+ associate_attribute_values_to_instance(product, color_attribute, values[0], values[1])# Ensure the new assignment was created- assert new_assignment.values.count() == 2- assert list(- new_assignment.productvalueassignment.values_list("value_id", "product_id")- ) == [(values[0].pk, product.id), (values[1].pk, product.id)]+ assert product.attributevalues.count() == 2+ assert list(product.attributevalues.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 d87578f4d9..7b5012c809 100644--- a/saleor/attribute/utils.py+++ b/saleor/attribute/utils.py@@ -1,5 +1,5 @@from collections.abc import Iterable-from typing import TYPE_CHECKING, Union+from typing import Unionfrom django.db.models.expressions import Exists, OuterRef@@ -7,44 +7,22 @@ from ..page.models import Pagefrom ..product.models import Product, ProductVariantfrom .models import (AssignedPageAttributeValue,- AssignedProductAttribute,AssignedProductAttributeValue,AssignedVariantAttribute,AssignedVariantAttributeValue,Attribute,AttributeValue,+ AttributeVariant,)-AttributeAssignmentType = Union[AssignedVariantAttribute, AssignedProductAttribute]T_INSTANCE = Union[Product, ProductVariant, Page]-if TYPE_CHECKING:- from .models import AttributePage, AttributeProduct, AttributeVariant---def disassociate_attributes_from_instance(- instance: T_INSTANCE,- *attributes: Attribute,-) -> None:- """Remove attribute assigned to an instance.-- This has to remove a FK to Attribute from Page instance and- remove all value assignments related to that same product and attribute.- """- values = AttributeValue.objects.filter(- attribute_id__in=[attr.id for attr in attributes]- )- AssignedPageAttributeValue.objects.filter(- Exists(values.filter(id=OuterRef("value_id"))),- page_id=instance.pk,- ).delete()-def associate_attribute_values_to_instance(instance: T_INSTANCE,attribute: Attribute,*values: AttributeValue,-) -> Union[None, AttributeAssignmentType]:+) -> Union[None, AssignedVariantAttribute]:"""Assign given attribute values to a product or variant.Note: be aware this function invokes the ``set`` method on the instance's@@ -61,7 +39,7 @@ def associate_attribute_values_to_instance(def validate_attribute_owns_values(attribute: Attribute, value_ids: set[int]) -> None:- """Check given value IDs are belonging to the given attribute.+ """Check if given value IDs belong to the given Attribute.:raise: AssertionError"""@@ -78,7 +56,7 @@ def _associate_attribute_to_instance(instance: T_INSTANCE,attribute: Attribute,*values: AttributeValue,-) -> Union[None, AttributeAssignmentType]:+) -> Union[None, AssignedVariantAttribute]:"""Associate a given attribute to an instance.For a given instance assign an attribute to it and set values based on *values.@@ -93,52 +71,71 @@ def _associate_attribute_to_instance("""if isinstance(instance, Page):# Clear all assignments that don't match the values we'd like to assign+ value_ids = [value.pk for value in values]values_qs = AttributeValue.objects.filter(attribute_id=attribute.pk)AssignedPageAttributeValue.objects.filter(Exists(values_qs.filter(id=OuterRef("value_id"))),page_id=instance.pk,- ).exclude(value__in=values).delete()+ ).exclude(value_id__in=value_ids).delete()# Create new assignments- for value in values:- AssignedPageAttributeValue.objects.get_or_create(page=instance, value=value)+ # Spend on db query to check values that are in the db so that we can use bulk_create+ # to set the new assignments+ # This code will be able to use bulk_create option ignore_conflicts once+ # unique_together is set for product + value on AssignedProductAttributeValue+ existing_page_values = AssignedPageAttributeValue.objects.filter(+ page=instance, value_id__in=value_ids+ ).values_list("value_id", flat=True)+ new_values = list(set(value_ids) - set(existing_page_values))++ AssignedPageAttributeValue.objects.bulk_create(+ AssignedPageAttributeValue(page=instance, value_id=value_id)+ for value_id in new_values+ )sort_assigned_attribute_values(instance, attribute, values)return None- assignment: AttributeAssignmentType-if isinstance(instance, Product):- attribute_rel: Union[- "AttributeProduct", "AttributeVariant", "AttributePage"- ] = instance.product_type.attributeproduct.get(attribute_id=attribute.pk)-- assignment, _ = AssignedProductAttribute.objects.get_or_create(- product=instance, assignment=attribute_rel- )- assignment.values.set(values)-- sort_assigned_attribute_values_using_assignment(instance, assignment, values)+ # Clear all assignments that don't match the values we'd like to assign+ value_ids = [value.pk for value in values]- # 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+ values_qs = AttributeValue.objects.filter(attribute_id=attribute.pk)AssignedProductAttributeValue.objects.filter(- assignment_id=assignment.pk- ).update(product_id=instance.pk)+ Exists(values_qs.filter(id=OuterRef("value_id"))),+ product_id=instance.pk,+ ).exclude(value_id__in=value_ids).delete()- return assignment+ # Create new assignments+ # Spend on db query to check values that are in the db so that we can use bulk_create+ # to set the new assignments+ # This code will be able to use bulk_create option ignore_conflicts once+ # unique_together is set for product + value on AssignedProductAttributeValue+ existing_product_values = AssignedProductAttributeValue.objects.filter(+ product=instance, value_id__in=value_ids+ ).values_list("value_id", flat=True)+ new_values = list(set(value_ids) - set(existing_product_values))++ AssignedProductAttributeValue.objects.bulk_create(+ AssignedProductAttributeValue(product=instance, value_id=value_id)+ for value_id in new_values+ )++ sort_assigned_attribute_values(instance, attribute, values)+ return Noneif isinstance(instance, ProductVariant):- attribute_variant = instance.product.product_type.attributevariant.get(- attribute_id=attribute.pk+ assignment: AssignedVariantAttribute++ attribute_variant = AttributeVariant.objects.get(+ attribute_id=attribute.pk,+ product_type_id=instance.product.product_type_id,)assignment, _ = AssignedVariantAttribute.objects.get_or_create(variant=instance, assignment=attribute_variant)assignment.values.set(values)-sort_assigned_attribute_values_using_assignment(instance, assignment, values)return assignment@@ -146,14 +143,13 @@ def _associate_attribute_to_instance(def sort_assigned_attribute_values_using_assignment(- instance: T_INSTANCE,- assignment: AttributeAssignmentType,+ instance: ProductVariant,+ assignment: AssignedVariantAttribute,values: Iterable[AttributeValue],) -> None:"""Sort assigned attribute values based on values list order."""instance_to_value_assignment_mapping = {"ProductVariant": ("variantvalueassignment", AssignedVariantAttributeValue),- "Product": ("productvalueassignment", AssignedProductAttributeValue),}assignment_lookup, assignment_model = instance_to_value_assignment_mapping[instance.__class__.__name__@@ -163,6 +159,7 @@ def sort_assigned_attribute_values_using_assignment(values_assignment = list(getattr(assignment, assignment_lookup).select_related("value"))+values_assignment.sort(key=lambda e: values_pks.index(e.value.pk))for index, value_assignment in enumerate(values_assignment):value_assignment.sort_order = index@@ -171,20 +168,41 @@ def sort_assigned_attribute_values_using_assignment(def sort_assigned_attribute_values(- instance: Page,+ instance: Union[Page, Product],attribute: Attribute,values: Iterable[AttributeValue],) -> None:values_pks = [value.pk for value in values]-values_qs = AttributeValue.objects.filter(attribute_id=attribute.pk)- values_assignment = list(- instance.attributevalues.filter(- Exists(values_qs.filter(id=OuterRef("value_id"))),++ if isinstance(instance, Page):+ assigned_page_values = list(+ AssignedPageAttributeValue.objects.filter(+ Exists(values_qs.filter(id=OuterRef("value_id"))),+ page_id=instance.pk,+ ).iterator())- )- values_assignment.sort(key=lambda e: values_pks.index(e.value_id))- for index, value_assignment in enumerate(values_assignment):- value_assignment.sort_order = index+ assigned_page_values.sort(key=lambda e: values_pks.index(e.value_id))+ for index, page_value_assignment in enumerate(assigned_page_values):+ page_value_assignment.sort_order = index+ AssignedPageAttributeValue.objects.bulk_update(+ assigned_page_values,+ ["sort_order"],+ )+ return- AssignedPageAttributeValue.objects.bulk_update(values_assignment, ["sort_order"])+ if isinstance(instance, Product):+ assigned_product_values = list(+ AssignedProductAttributeValue.objects.filter(+ Exists(values_qs.filter(id=OuterRef("value_id"))),+ product=instance.pk,+ ).iterator()+ )+ assigned_product_values.sort(key=lambda e: values_pks.index(e.value_id))+ for index, product_value_assignment in enumerate(assigned_product_values):+ product_value_assignment.sort_order = index+ AssignedProductAttributeValue.objects.bulk_update(+ assigned_product_values,+ ["sort_order"],+ )+ returndiff --git a/saleor/core/utils/random_data.py b/saleor/core/utils/random_data.pyindex 8a155b5225..6609587d2f 100644--- a/saleor/core/utils/random_data.py+++ b/saleor/core/utils/random_data.py@@ -30,7 +30,6 @@ from ...account.search import ()from ...account.utils import store_user_addressfrom ...attribute.models import (- AssignedProductAttribute,AssignedProductAttributeValue,AssignedVariantAttribute,AssignedVariantAttributeValue,@@ -366,21 +365,12 @@ def assign_attributes_to_page_types(association_model.objects.update_or_create(pk=pk, defaults=defaults)-def assign_attributes_to_products(product_attributes):- for value in product_attributes:- pk = value["pk"]- defaults = dict(value["fields"])- defaults["product_id"] = defaults.pop("product")- defaults["assignment_id"] = defaults.pop("assignment")- AssignedProductAttribute.objects.update_or_create(pk=pk, defaults=defaults)--def assign_attribute_values_to_products(values):for value in values:pk = value["pk"]defaults = dict(value["fields"])defaults["value_id"] = defaults.pop("value")- defaults["assignment_id"] = defaults.pop("assignment")+ defaults["product_id"] = defaults.pop("product")AssignedProductAttributeValue.objects.update_or_create(pk=pk, defaults=defaults)@@ -443,9 +433,6 @@ def create_products_by_schema(placeholder_dir, create_images):assign_attributes_to_page_types(AttributePage, attributes=types["attribute.attributepage"])- assign_attributes_to_products(- product_attributes=types["attribute.assignedproductattribute"]- )assign_attribute_values_to_products(types["attribute.assignedproductattributevalue"])diff --git a/saleor/csv/tests/export/products_data/test_get_products_data.py b/saleor/csv/tests/export/products_data/test_get_products_data.pyindex 80128dcccf..7eb6ce1573 100644--- a/saleor/csv/tests/export/products_data/test_get_products_data.py+++ b/saleor/csv/tests/export/products_data/test_get_products_data.py@@ -4,7 +4,9 @@ import graphenefrom measurement.measures import Weightfrom .....attribute.models import Attribute, AttributeValue-from .....attribute.utils import associate_attribute_values_to_instance+from .....attribute.utils import (+ associate_attribute_values_to_instance,+)from .....channel.models import Channelfrom .....product.models import Product, ProductVariant, VariantMediafrom .....warehouse.models import Warehouse@@ -410,11 +412,7 @@ def test_get_products_data_for_specified_warehouses_channels_and_attributes(associate_attribute_values_to_instance(product, numeric_attribute, numeric_value_2)# create assigned product without values- associate_attribute_values_to_instance(- product, color_attribute, color_attribute.values.first()- )- assigned_product = product.attributes.get(assignment__attribute=color_attribute)- assigned_product.values.clear()+ associate_attribute_values_to_instance(product, color_attribute)# add swatch attributeswatch_value_1 = swatch_attribute.values.first()@@ -445,6 +443,7 @@ def test_get_products_data_for_specified_warehouses_channels_and_attributes(product_data = add_product_attribute_data_to_expected_data(product_data, product, attribute_ids)+product_data = add_channel_to_expected_product_data(product_data, product, channel_ids)diff --git a/saleor/csv/tests/export/products_data/test_handle_relations_data.py b/saleor/csv/tests/export/products_data/test_handle_relations_data.pyindex 03bebad8d9..23971360e0 100644--- a/saleor/csv/tests/export/products_data/test_handle_relations_data.py+++ b/saleor/csv/tests/export/products_data/test_handle_relations_data.py@@ -1,7 +1,11 @@from datetime import datetimefrom unittest.mock import patch-from .....attribute.models import Attribute, AttributeValue+from .....attribute.models import (+ Attribute,+ AttributeValue,+)+from .....attribute.tests.model_helpers import get_product_attributesfrom .....attribute.utils import associate_attribute_values_to_instancefrom .....product.models import Product, ProductMedia, ProductVariant, VariantMediafrom .....tests.utils import dummy_editorjs@@ -186,8 +190,7 @@ def test_prepare_products_relations_data(ProductExportFields.HEADERS_TO_FIELDS_MAPPING["product_many_to_many"].values())attribute_ids = [- str(attr.assignment.attribute.pk)- for attr in product_with_image.attributes.all()+ str(attr.pk) for attr in get_product_attributes(product_with_image)]channel_ids = [str(channel_PLN.pk), str(channel_USD.pk)]@@ -209,6 +212,7 @@ def test_prepare_products_relations_data(expected_result = add_product_attribute_data_to_expected_data(expected_result, product_with_image, attribute_ids, pk)+expected_result = add_channel_to_expected_product_data(expected_result, product_with_image, channel_ids, pk)@@ -250,8 +254,7 @@ def test_prepare_products_relations_data_only_attributes_ids(qs = Product.objects.all()fields = {"name"}attribute_ids = [- str(attr.assignment.attribute.pk)- for attr in product_with_image.attributes.all()+ str(attr.pk) for attr in get_product_attributes(product_with_image)]channel_ids = []@@ -293,29 +296,6 @@ def test_prepare_products_relations_data_only_channel_ids(assert result == expected_result-def test_prepare_products_relations_data_attribute_without_values(- product,- channel_USD,- channel_PLN,-):- # given- pk = product.pk-- attribute_product = product.attributes.first()- attribute_product.values.clear()- attribute = attribute_product.assignment.attribute-- qs = Product.objects.all()- fields = {"name"}- attribute_ids = [str(attribute.pk)]-- # when- result = prepare_products_relations_data(qs, fields, attribute_ids, [])-- # then- assert result == {pk: {f"{attribute.slug} (product attribute)": ""}}--@patch("saleor.csv.utils.products_data.prepare_variants_relations_data")def test_get_variants_relations_data(prepare_variants_data_mocked, product_list):# givendiff --git a/saleor/csv/tests/export/products_data/utils.py b/saleor/csv/tests/export/products_data/utils.pyindex 9f6c3c6a41..f52fb651ed 100644--- a/saleor/csv/tests/export/products_data/utils.py+++ b/saleor/csv/tests/export/products_data/utils.py@@ -1,17 +1,47 @@+from collections import defaultdict++from django.db.models import prefetch_related_objects+from django.db.models.expressions import Exists, OuterRef+from .....attribute import AttributeInputType+from .....attribute.models import (+ AssignedProductAttributeValue,+ Attribute,+ AttributeProduct,+)from .....core.utils.editorjs import clean_editor_jsdef add_product_attribute_data_to_expected_data(data, product, attribute_ids, pk=None):- for assigned_attribute in product.attributes.all():- if assigned_attribute:- header = f"{assigned_attribute.attribute.slug} (product attribute)"- if str(assigned_attribute.attribute.pk) in attribute_ids:- value = get_attribute_value(assigned_attribute)- if pk:- data[pk][header] = value- else:- data[header] = value+ product_attributes = AttributeProduct.objects.filter(+ product_type_id=product.product_type_id+ )+ attributes = (+ Attribute.objects.filter(+ Exists(product_attributes.filter(attribute_id=OuterRef("id")))+ )+ .order_by("attributeproduct__sort_order")+ .iterator()+ )+ assigned_values = AssignedProductAttributeValue.objects.filter(+ product_id=product.pk+ )+ prefetch_related_objects(assigned_values, "value")++ values_map = defaultdict(list)+ for av in assigned_values:+ values_map[av.value.attribute_id].append(av.value)++ for attribute in attributes:+ header = f"{attribute.slug} (product attribute)"+ attribute_values = values_map[attribute.id]+ value_instance = attribute_values[0] if attribute_values else None+ if str(attribute.pk) in attribute_ids and value_instance:+ value = get_attribute_value(attribute, value_instance)+ if pk:+ data[pk][header] = value+ else:+ data[header] = valuereturn data@@ -19,7 +49,9 @@ def add_variant_attribute_data_to_expected_data(data, variant, attribute_ids, pkfor assigned_attribute in variant.attributes.all():header = f"{assigned_attribute.attribute.slug} (variant attribute)"if str(assigned_attribute.attribute.pk) in attribute_ids:- value = get_attribute_value(assigned_attribute)+ value_instance = assigned_attribute.values.first()+ attribute = assigned_attribute.attribute+ value = get_attribute_value(attribute, value_instance)if pk:data[pk][header] = valueelse:@@ -28,11 +60,9 @@ def add_variant_attribute_data_to_expected_data(data, variant, attribute_ids, pkreturn data-def get_attribute_value(assigned_attribute):- value_instance = assigned_attribute.values.first()+def get_attribute_value(attribute, value_instance):if not value_instance:return ""- attribute = assigned_attribute.attributeif attribute.input_type == AttributeInputType.FILE:value = "http://mirumee.com/media/" + value_instance.file_urlelif attribute.input_type == AttributeInputType.REFERENCE:diff --git a/saleor/csv/utils/__init__.py b/saleor/csv/utils/__init__.pyindex 208858a5d1..4dfa9c6440 100644--- a/saleor/csv/utils/__init__.py+++ b/saleor/csv/utils/__init__.py@@ -25,21 +25,21 @@ class ProductExportFields:}PRODUCT_ATTRIBUTE_FIELDS = {- "value_slug": "attributes__values__slug",- "value_name": "attributes__values__name",- "file_url": "attributes__values__file_url",- "rich_text": "attributes__values__rich_text",- "value": "attributes__values__value",- "boolean": "attributes__values__boolean",- "date_time": "attributes__values__date_time",- "slug": "attributes__assignment__attribute__slug",- "input_type": "attributes__assignment__attribute__input_type",- "entity_type": "attributes__assignment__attribute__entity_type",- "unit": "attributes__assignment__attribute__unit",- "attribute_pk": "attributes__assignment__attribute__pk",- "reference_page": "attributes__values__reference_page",- "reference_product": "attributes__values__reference_product",- "reference_variant": "attributes__values__reference_variant",+ "value_slug": "attributevalues__value__slug",+ "value_name": "attributevalues__value__name",+ "file_url": "attributevalues__value__file_url",+ "rich_text": "attributevalues__value__rich_text",+ "value": "attributevalues__value__value",+ "boolean": "attributevalues__value__boolean",+ "date_time": "attributevalues__value__date_time",+ "slug": "attributevalues__value__attribute__slug",+ "input_type": "attributevalues__value__attribute__input_type",+ "entity_type": "attributevalues__value__attribute__entity_type",+ "unit": "attributevalues__value__attribute__unit",+ "attribute_pk": "attributevalues__value__attribute__pk",+ "reference_page": "attributevalues__value__reference_page",+ "reference_product": "attributevalues__value__reference_product",+ "reference_variant": "attributevalues__value__reference_variant",}PRODUCT_CHANNEL_LISTING_FIELDS = {diff --git a/saleor/csv/utils/export.py b/saleor/csv/utils/export.pyindex 1424b59af5..3c8e93ef2d 100644--- a/saleor/csv/utils/export.py+++ b/saleor/csv/utils/export.py@@ -197,7 +197,7 @@ def export_products_in_batches(for batch_pks in queryset_in_batches(queryset):product_batch = Product.objects.filter(pk__in=batch_pks).prefetch_related(- "attributes",+ "attributevalues","variants","collections","media",diff --git a/saleor/graphql/attribute/bulk_mutations.py b/saleor/graphql/attribute/bulk_mutations.pyindex b6c0e9a135..e729438c25 100644--- a/saleor/graphql/attribute/bulk_mutations.py+++ b/saleor/graphql/attribute/bulk_mutations.py@@ -51,13 +51,6 @@ class AttributeBulkDelete(ModelBulkDeleteMutation):@classmethoddef get_product_ids_to_update(cls, attribute_pks):- attribute_product = models.AttributeProduct.objects.filter(- attribute_id__in=attribute_pks- )- assigned_product_attrs = models.AssignedProductAttribute.objects.filter(- Exists(attribute_product.filter(id=OuterRef("assignment_id")))- )-attribute_variant = models.AttributeVariant.objects.filter(attribute_id__in=attribute_pks)@@ -68,9 +61,15 @@ class AttributeBulkDelete(ModelBulkDeleteMutation):Exists(assigned_variant_attrs.filter(variant_id=OuterRef("id"))))+ attribute_product = models.AttributeProduct.objects.filter(+ attribute_id__in=attribute_pks+ )+product_ids = product_models.Product.objects.filter(- Exists(assigned_product_attrs.filter(product_id=OuterRef("id")))- | Q(Exists(variants.filter(product_id=OuterRef("id"))))+ Exists(+ attribute_product.filter(product_type_id=OuterRef("product_type_id"))+ )+ | Exists(variants.filter(product_id=OuterRef("id")))).values_list("id", flat=True)return list(product_ids)@@ -142,9 +141,6 @@ class AttributeValueBulkDelete(ModelBulkDeleteMutation):assigned_product_values = models.AssignedProductAttributeValue.objects.filter(value_id__in=value_pks)- assigned_product_attrs = models.AssignedProductAttribute.objects.filter(- Exists(assigned_product_values.filter(assignment_id=OuterRef("id")))- )assigned_variant_values = models.AssignedVariantAttributeValue.objects.filter(value_id__in=value_pks@@ -157,7 +153,7 @@ class AttributeValueBulkDelete(ModelBulkDeleteMutation):)product_ids = product_models.Product.objects.filter(- Exists(assigned_product_attrs.filter(product_id=OuterRef("id")))+ Exists(assigned_product_values.filter(product_id=OuterRef("id")))| Q(Exists(variants.filter(product_id=OuterRef("id"))))).values_list("id", flat=True)return list(product_ids)diff --git a/saleor/graphql/attribute/mutations/attribute_value_delete.py b/saleor/graphql/attribute/mutations/attribute_value_delete.pyindex 81832b351a..f92141774f 100644--- a/saleor/graphql/attribute/mutations/attribute_value_delete.py+++ b/saleor/graphql/attribute/mutations/attribute_value_delete.py@@ -65,7 +65,7 @@ class AttributeValueDelete(ModelDeleteMutation, ModelWithExtRefMutation):Exists(instance.variantassignments.filter(variant_id=OuterRef("id"))))product_ids = product_models.Product.objects.filter(- Q(Exists(instance.productassignments.filter(product_id=OuterRef("id"))))+ Q(Exists(instance.productvalueassignment.filter(product_id=OuterRef("id"))))| Q(Exists(variants.filter(product_id=OuterRef("id"))))).values_list("id", flat=True)return list(product_ids)diff --git a/saleor/graphql/attribute/mutations/attribute_value_update.py b/saleor/graphql/attribute/mutations/attribute_value_update.pyindex 34b0fb0859..9a895758fb 100644--- a/saleor/graphql/attribute/mutations/attribute_value_update.py+++ b/saleor/graphql/attribute/mutations/attribute_value_update.py@@ -99,6 +99,7 @@ class AttributeValueUpdate(AttributeValueCreate, ModelWithExtRefMutation):)# SELECT … FOR UPDATE needs to lock rows in a consistent order# to avoid deadlocks between updates touching the same rows.+qs = (product_models.Product.objects.select_for_update(of=("self",)).filter(@@ -106,7 +107,7 @@ class AttributeValueUpdate(AttributeValueCreate, ModelWithExtRefMutation):& (Q(Exists(- instance.productassignments.filter(+ instance.productvalueassignment.filter(product_id=OuterRef("id")))diff --git a/saleor/graphql/attribute/tests/mutations/test_attribute_value_delete.py b/saleor/graphql/attribute/tests/mutations/test_attribute_value_delete.pyindex 3957611db9..3021227271 100644--- a/saleor/graphql/attribute/tests/mutations/test_attribute_value_delete.py+++ b/saleor/graphql/attribute/tests/mutations/test_attribute_value_delete.py@@ -6,6 +6,10 @@ import pytestfrom django.utils.functional import SimpleLazyObjectfrom freezegun import freeze_time+from .....attribute.tests.model_helpers import (+ get_product_attribute_values,+ get_product_attributes,+)from .....attribute.utils import associate_attribute_values_to_instancefrom .....core.utils.json_serializer import CustomJsonEncoderfrom .....webhook.event_types import WebhookEventAsyncType@@ -52,7 +56,8 @@ def test_delete_attribute_value_update_search_index_dirty_in_product(permission_manage_product_types_and_attributes,):# given- value = product.attributes.all()[0].values.first()+ first_attribute = get_product_attributes(product).first()+ value = get_product_attribute_values(product, first_attribute).first()query = ATTRIBUTE_VALUE_DELETE_MUTATIONnode_id = graphene.Node.to_global_id("AttributeValue", value.id)variables = {"id": node_id}@@ -64,8 +69,6 @@ def test_delete_attribute_value_update_search_index_dirty_in_product(product.refresh_from_db(fields=["search_index_dirty"])# then- with pytest.raises(value._meta.model.DoesNotExist):- value.refresh_from_db()assert product.search_index_dirty is Truediff --git a/saleor/graphql/attribute/tests/mutations/test_attribute_value_update.py b/saleor/graphql/attribute/tests/mutations/test_attribute_value_update.pyindex ed4670f2f7..c33f8c3bc9 100644--- a/saleor/graphql/attribute/tests/mutations/test_attribute_value_update.py+++ b/saleor/graphql/attribute/tests/mutations/test_attribute_value_update.py@@ -8,6 +8,10 @@ from django.utils.text import slugifyfrom freezegun import freeze_timefrom .....attribute.error_codes import AttributeErrorCode+from .....attribute.tests.model_helpers import (+ get_product_attribute_values,+ get_product_attributes,+)from .....attribute.utils import associate_attribute_values_to_instancefrom .....core.utils.json_serializer import CustomJsonEncoderfrom .....webhook.event_types import WebhookEventAsyncType@@ -93,7 +97,10 @@ def test_update_attribute_value_update_search_index_dirty_in_product():# givenquery = UPDATE_ATTRIBUTE_VALUE_MUTATION- value = product.attributes.all()[0].values.first()++ first_attribute = get_product_attributes(product).first()+ value = get_product_attribute_values(product, first_attribute).first()+node_id = graphene.Node.to_global_id("AttributeValue", value.id)name = "Crimson name"variables = {"input": {"name": name}, "id": node_id}diff --git a/saleor/graphql/attribute/tests/queries/test_attributes_sort.py b/saleor/graphql/attribute/tests/queries/test_attributes_sort.pyindex 2a4fdf8125..2f782152a0 100644--- a/saleor/graphql/attribute/tests/queries/test_attributes_sort.py+++ b/saleor/graphql/attribute/tests/queries/test_attributes_sort.py@@ -1,8 +1,7 @@import graphene-import pytestfrom .....attribute import AttributeType-from .....attribute.models import Attribute+from .....attribute.models import AssignedProductAttributeValue, Attributefrom .....attribute.utils import associate_attribute_values_to_instancefrom ....tests.utils import get_graphql_content@@ -56,38 +55,24 @@ def test_sort_attributes_by_default_sorting(api_client):assert attributes[1]["node"]["slug"] == "b"[email protected]("is_variant", [True, False])-def test_attributes_of_products_are_sorted(- user_api_client, product, color_attribute, is_variant, channel_USD+def test_attributes_of_products_are_sorted_on_variant(+ user_api_client, product, color_attribute, channel_USD):"""Ensures the attributes of products and variants are sorted."""variant = product.variants.first()- if is_variant:- query = """- query($id: ID!, $channel: String) {- productVariant(id: $id, channel: $channel) {- attributes {- attribute {- id- }+ query = """+ query($id: ID!, $channel: String) {+ productVariant(id: $id, channel: $channel) {+ attributes {+ attribute {+ id}- }}- """- else:- query = """- query($id: ID!, $channel: String) {- product(id: $id, channel: $channel) {- attributes {- attribute {- id- }- }- }}- """+ }+ """# Create a dummy attribute with a higher ID# This will allow us to make sure it is always the last attribute@@ -95,36 +80,85 @@ def test_attributes_of_products_are_sorted(other_attribute = Attribute.objects.create(name="Other", slug="other")# Add the attribute to the product type- if is_variant:- product.product_type.variant_attributes.set([color_attribute, other_attribute])- else:- product.product_type.product_attributes.set([color_attribute, other_attribute])+ product.product_type.variant_attributes.set([color_attribute, other_attribute])# Retrieve the M2M object for the attribute vs the product type- if is_variant:- m2m_rel_other_attr = other_attribute.attributevariant.last()- else:- m2m_rel_other_attr = other_attribute.attributeproduct.last()+ m2m_rel_other_attr = other_attribute.attributevariant.last()# Push the last attribute to the top and let the others to Nonem2m_rel_other_attr.sort_order = 0m2m_rel_other_attr.save(update_fields=["sort_order"])# Assign attributes to the product- node = variant if is_variant else product # type: Union[Product, ProductVariant]- node.attributesrelated.clear()associate_attribute_values_to_instance(- node, color_attribute, color_attribute.values.first()+ variant, color_attribute, color_attribute.values.first()+ )++ # Sort the database attributes by their sort order and ID (when None)+ expected_order = [other_attribute.pk, color_attribute.pk]++ # Make the node ID+ node_id = graphene.Node.to_global_id("ProductVariant", variant.pk)++ # Retrieve the attributes+ data = get_graphql_content(+ user_api_client.post_graphql(+ query, {"id": node_id, "channel": channel_USD.slug}+ )+ )["data"]+ attributes = data["productVariant"]["attributes"]+ actual_order = [+ int(graphene.Node.from_global_id(attr["attribute"]["id"])[1])+ for attr in attributes+ ]++ # Compare the received data against our expectations+ assert actual_order == expected_order+++def test_attributes_of_products_are_sorted_on_product(+ user_api_client, product, color_attribute, channel_USD+):+ """Ensures the attributes of products and variants are sorted."""++ query = """+ query($id: ID!, $channel: String) {+ product(id: $id, channel: $channel) {+ attributes {+ attribute {+ id+ }+ }+ }+ }+ """++ # Create a dummy attribute with a higher ID+ # This will allow us to make sure it is always the last attribute+ # when sorted by ID. Thus, we are sure the query is actually passing the test.+ other_attribute = Attribute.objects.create(name="Other", slug="other")++ # Add the attribute to the product type+ product.product_type.product_attributes.set([color_attribute, other_attribute])++ # Retrieve the M2M object for the attribute vs the product type+ m2m_rel_other_attr = other_attribute.attributeproduct.last()++ # Push the last attribute to the top and set the others to None+ m2m_rel_other_attr.sort_order = 0+ m2m_rel_other_attr.save(update_fields=["sort_order"])++ # Assign attributes to the product+ AssignedProductAttributeValue.objects.filter(product_id=product.pk).delete()+ associate_attribute_values_to_instance(+ product, color_attribute, color_attribute.values.first())# Sort the database attributes by their sort order and ID (when None)expected_order = [other_attribute.pk, color_attribute.pk]# Make the node ID- if is_variant:- node_id = graphene.Node.to_global_id("ProductVariant", variant.pk)- else:- node_id = graphene.Node.to_global_id("Product", product.pk)+ node_id = graphene.Node.to_global_id("Product", product.pk)# Retrieve the attributesdata = get_graphql_content(@@ -132,7 +166,7 @@ def test_attributes_of_products_are_sorted(query, {"id": node_id, "channel": channel_USD.slug}))["data"]- attributes = data["productVariant" if is_variant else "product"]["attributes"]+ attributes = data["product"]["attributes"]actual_order = [int(graphene.Node.from_global_id(attr["attribute"]["id"])[1])for attr in attributesdiff --git a/saleor/graphql/attribute/utils.py b/saleor/graphql/attribute/utils.pyindex 2a9b76292b..30883965af 100644--- a/saleor/graphql/attribute/utils.py+++ b/saleor/graphql/attribute/utils.py@@ -8,6 +8,7 @@ from typing import TYPE_CHECKING, Optional, Unionimport graphenefrom django.core.exceptions import ValidationErrorfrom django.db.models import Q+from django.db.models.expressions import Exists, OuterReffrom django.db.utils import IntegrityErrorfrom django.template.defaultfilters import truncatecharsfrom django.utils import timezone@@ -15,11 +16,10 @@ from django.utils.text import slugifyfrom graphql.error import GraphQLErrorfrom text_unidecode import unidecode-from ...attribute import AttributeEntityType, AttributeInputType, AttributeType+from ...attribute import AttributeEntityType, AttributeInputTypefrom ...attribute import models as attribute_modelsfrom ...attribute.utils import (associate_attribute_values_to_instance,- disassociate_attributes_from_instance,)from ...core.utils import (generate_unique_slug,@@ -120,8 +120,11 @@ class AttributeAssignmentMixin:):"""Retrieve attributes nodes from given global IDs or external reference."""- qs = qs.filter(Q(pk__in=pks) | Q(external_reference__in=external_references))- nodes: list[attribute_models.Attribute] = list(qs)+ nodes: list[attribute_models.Attribute] = list(+ qs.filter(+ Q(pk__in=pks) | Q(external_reference__in=external_references)+ ).iterator()+ )if not nodes:raise ValidationError(@@ -774,14 +777,16 @@ class PageAttributeAssignmentMixin(AttributeAssignmentMixin):lookup_field: str,value,):- return (- attribute.values.filter(- pagevalueassignment__page_id=instance.pk,- **{lookup_field: value},- ).first()- or None+ assigned_values = attribute_models.AssignedPageAttributeValue.objects.filter(+ page_id=instance.pk)+ return attribute_models.AttributeValue.objects.filter(+ Exists(assigned_values.filter(value_id=OuterRef("id"))),+ attribute_id=attribute.pk,+ **{lookup_field: value},+ ).first()+@classmethoddef save(cls,@@ -807,7 +812,6 @@ class PageAttributeAssignmentMixin(AttributeAssignmentMixin):AttributeInputType.REFERENCE: cls._pre_save_reference_values,AttributeInputType.RICH_TEXT: cls._pre_save_rich_text_values,}- clean_assignment = []for attribute, attr_values in cleaned_input:is_handled_by_values_field = (@@ -828,18 +832,76 @@ class PageAttributeAssignmentMixin(AttributeAssignmentMixin):associate_attribute_values_to_instance(instance, attribute, *attribute_values)- if not attribute_values:- clean_assignment.append(attribute)- # drop attribute assignment model when values are unassigned from instance- if clean_assignment:- disassociate_attributes_from_instance(instance, *clean_assignment)+class ProductAttributeAssignmentMixin(AttributeAssignmentMixin):+ # TODO: merge the code here with the mixin above+ # when all attribute relations are cleaned up-def get_variant_selection_attributes(qs: "QuerySet") -> "QuerySet":- return qs.filter(- type=AttributeType.PRODUCT_TYPE, attributevariant__variant_selection=True- )+ @classmethod+ def _get_assigned_attribute_value_if_exists(+ cls,+ instance: T_INSTANCE,+ attribute: attribute_models.Attribute,+ lookup_field: str,+ value,+ ):+ assigned_values = attribute_models.AssignedProductAttributeValue.objects.filter(+ product_id=instance.pk+ )++ return attribute_models.AttributeValue.objects.filter(+ Exists(assigned_values.filter(value_id=OuterRef("id"))),+ attribute_id=attribute.pk,+ **{lookup_field: value},+ ).first()++ @classmethod+ def save(+ cls,+ instance: T_INSTANCE,+ cleaned_input: T_INPUT_MAP,+ ):+ """Save the cleaned input into the database against the given instance.++ Note: this should always be ran inside a transaction.++ :param instance: the product or variant to associate the attribute against.+ :param cleaned_input: the cleaned user input (refer to clean_attributes)+ """+ pre_save_methods_mapping = {+ AttributeInputType.BOOLEAN: cls._pre_save_boolean_values,+ AttributeInputType.DATE: cls._pre_save_date_time_values,+ AttributeInputType.DATE_TIME: cls._pre_save_date_time_values,+ AttributeInputType.DROPDOWN: cls._pre_save_dropdown_value,+ AttributeInputType.SWATCH: cls._pre_save_swatch_value,+ AttributeInputType.FILE: cls._pre_save_file_value,+ AttributeInputType.NUMERIC: cls._pre_save_numeric_values,+ AttributeInputType.MULTISELECT: cls._pre_save_multiselect_values,+ AttributeInputType.PLAIN_TEXT: cls._pre_save_plain_text_values,+ AttributeInputType.REFERENCE: cls._pre_save_reference_values,+ AttributeInputType.RICH_TEXT: cls._pre_save_rich_text_values,+ }++ for attribute, attr_values in cleaned_input:+ is_handled_by_values_field = (+ attr_values.values+ and attribute.input_type+ in (+ AttributeInputType.DROPDOWN,+ AttributeInputType.MULTISELECT,+ AttributeInputType.SWATCH,+ )+ )+ if is_handled_by_values_field:+ attribute_values = cls._pre_save_values(attribute, attr_values)+ else:+ pre_save_func = pre_save_methods_mapping[attribute.input_type]+ attribute_values = pre_save_func(instance, attribute, attr_values)++ associate_attribute_values_to_instance(+ instance, attribute, *attribute_values+ )def prepare_attribute_values(attribute: attribute_models.Attribute, values: list[str]):diff --git a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.pyindex b21b9d5d82..c7a2faa7b7 100644--- a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py+++ b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py@@ -1333,7 +1333,7 @@ def test_complete_checkout_with_digital_line(@pytest.mark.django_db@pytest.mark.count_queries(autouse=False)def test_customer_complete_checkout(- api_client, checkout_with_charged_payment, count_queries, customer_user+ api_client, checkout_with_charged_payment, customer_user, count_queries):query = COMPLETE_CHECKOUT_MUTATIONcheckout = checkout_with_charged_payment@@ -1350,7 +1350,7 @@ def test_customer_complete_checkout(@pytest.mark.django_db@pytest.mark.count_queries(autouse=False)def test_customer_complete_checkout_for_cc(- api_client, checkout_with_charged_payment_for_cc, count_queries, customer_user+ api_client, checkout_with_charged_payment_for_cc, customer_user, count_queries):query = COMPLETE_CHECKOUT_MUTATION_FOR_CCcheckout = checkout_with_charged_payment_for_ccdiff --git a/saleor/graphql/product/bulk_mutations/product_bulk_create.py b/saleor/graphql/product/bulk_mutations/product_bulk_create.pyindex 77de5fc6ba..bd2812fd3a 100644--- a/saleor/graphql/product/bulk_mutations/product_bulk_create.py+++ b/saleor/graphql/product/bulk_mutations/product_bulk_create.py@@ -24,7 +24,7 @@ from ....warehouse.models import Warehousefrom ....webhook.event_types import WebhookEventAsyncTypefrom ....webhook.utils import get_webhooks_for_eventfrom ...attribute.types import AttributeValueInput-from ...attribute.utils import AttributeAssignmentMixin+from ...attribute.utils import ProductAttributeAssignmentMixinfrom ...channel import ChannelContextfrom ...core.descriptions import ADDED_IN_313, PREVIEW_FEATURE, RICH_CONTENTfrom ...core.doc_category import DOC_CATEGORY_PRODUCTS@@ -288,7 +288,7 @@ class ProductBulkCreate(BaseMutation):if attributes := cleaned_input.get("attributes"):try:attributes_qs = cleaned_input["product_type"].product_attributes.all()- attributes = AttributeAssignmentMixin.clean_input(+ attributes = ProductAttributeAssignmentMixin.clean_input(attributes, attributes_qs)cleaned_input["attributes"] = attributes@@ -755,7 +755,7 @@ class ProductBulkCreate(BaseMutation):models.ProductChannelListing.objects.bulk_create(listings_to_create)for product, attributes in attributes_to_save:- AttributeAssignmentMixin.save(product, attributes)+ ProductAttributeAssignmentMixin.save(product, attributes)if variants_input_data:variants = cls.save_variants(info, variants_input_data)diff --git a/saleor/graphql/product/bulk_mutations/product_bulk_delete.py b/saleor/graphql/product/bulk_mutations/product_bulk_delete.pyindex 1cdee6cea2..743247d912 100644--- a/saleor/graphql/product/bulk_mutations/product_bulk_delete.py+++ b/saleor/graphql/product/bulk_mutations/product_bulk_delete.py@@ -2,6 +2,7 @@ from collections import defaultdictimport graphenefrom django.core.exceptions import ValidationError+from django.db.models.expressions import Exists, OuterReffrom ....attribute import AttributeInputTypefrom ....attribute import models as attribute_models@@ -80,9 +81,16 @@ class ProductBulkDelete(ModelBulkDeleteMutation):@staticmethoddef delete_assigned_attribute_values(instance_pks):+ assigned_values = attribute_models.AssignedProductAttributeValue.objects.filter(+ product_id__in=instance_pks+ )+ attributes = attribute_models.Attribute.objects.filter(+ input_type__in=AttributeInputType.TYPES_WITH_UNIQUE_VALUES+ )+attribute_models.AttributeValue.objects.filter(- productassignments__product_id__in=instance_pks,- attribute__input_type__in=AttributeInputType.TYPES_WITH_UNIQUE_VALUES,+ Exists(assigned_values.filter(value_id=OuterRef("id"))),+ Exists(attributes.filter(id=OuterRef("attribute_id"))),).delete()@classmethoddiff --git a/saleor/graphql/product/bulk_mutations/product_type_bulk_delete.py b/saleor/graphql/product/bulk_mutations/product_type_bulk_delete.pyindex df8328652a..91e28193bc 100644--- a/saleor/graphql/product/bulk_mutations/product_type_bulk_delete.py+++ b/saleor/graphql/product/bulk_mutations/product_type_bulk_delete.py@@ -1,6 +1,7 @@import graphenefrom django.core.exceptions import ValidationErrorfrom django.db.models import Q+from django.db.models.expressions import Exists, OuterReffrom ....attribute import AttributeInputTypefrom ....attribute import models as attribute_models@@ -43,10 +44,16 @@ class ProductTypeBulkDelete(ModelBulkDeleteMutation):@staticmethoddef delete_assigned_attribute_values(instance_pks):+ attributes = attribute_models.Attribute.objects.filter(+ input_type__in=AttributeInputType.TYPES_WITH_UNIQUE_VALUES+ )+ assigned_values = attribute_models.AssignedProductAttributeValue.objects.filter(+ product__product_type_id__in=instance_pks+ )attribute_models.AttributeValue.objects.filter(- Q(attribute__input_type__in=AttributeInputType.TYPES_WITH_UNIQUE_VALUES)- & (- Q(productassignments__assignment__product_type_id__in=instance_pks)+ Exists(attributes.filter(id=OuterRef("attribute_id"))),+ (+ Q(Exists(assigned_values.filter(value_id=OuterRef("id"))))| Q(variantassignments__assignment__product_type_id__in=instance_pks)- )+ ),).delete()diff --git a/saleor/graphql/product/dataloaders/attributes.py b/saleor/graphql/product/dataloaders/attributes.pyindex 26deb77b6b..6ced57dcf7 100644--- a/saleor/graphql/product/dataloaders/attributes.py+++ b/saleor/graphql/product/dataloaders/attributes.py@@ -3,7 +3,6 @@ from collections import defaultdictfrom promise import Promisefrom ....attribute.models import (- AssignedProductAttribute,AssignedProductAttributeValue,AssignedVariantAttribute,AssignedVariantAttributeValue,@@ -89,32 +88,6 @@ class VariantAttributesByProductTypeIdLoader(extra_fields = ["variant_selection"]-class AttributeProductsByProductTypeIdLoader(DataLoader):- """Loads AttributeProduct objects by product type ID."""-- context_key = "attributeproducts_by_producttype"-- def batch_load(self, keys):- requestor = get_user_or_app_from_context(self.context)- if (- requestor- and requestor.is_active- and requestor.has_perm(ProductPermissions.MANAGE_PRODUCTS)- ):- qs = AttributeProduct.objects.using(self.database_connection_name).all()- else:- qs = AttributeProduct.objects.using(self.database_connection_name).filter(- attribute__visible_in_storefront=True- )- attribute_products = qs.filter(product_type_id__in=keys)- producttype_to_attributeproducts = defaultdict(list)- for attribute_product in attribute_products:- producttype_to_attributeproducts[attribute_product.product_type_id].append(- attribute_product- )- return [producttype_to_attributeproducts[key] for key in keys]--class AttributeVariantsByProductTypeIdLoader(DataLoader):context_key = "attributevariants_by_producttype"@@ -139,32 +112,6 @@ class AttributeVariantsByProductTypeIdLoader(DataLoader):return [producttype_to_attributevariants[key] for key in keys]-class AssignedProductAttributesByProductIdLoader(DataLoader):- context_key = "assignedproductattributes_by_product"-- def batch_load(self, keys):- requestor = get_user_or_app_from_context(self.context)- if (- requestor- and requestor.is_active- and requestor.has_perm(ProductPermissions.MANAGE_PRODUCTS)- ):- qs = AssignedProductAttribute.objects.using(- self.database_connection_name- ).all()- else:- qs = AssignedProductAttribute.objects.using(- self.database_connection_name- ).filter(assignment__attribute__visible_in_storefront=True)- assigned_product_attributes = qs.filter(product_id__in=keys)- product_to_assignedproductattributes = defaultdict(list)- for assigned_product_attribute in assigned_product_attributes.iterator():- product_to_assignedproductattributes[- assigned_product_attribute.product_id- ].append(assigned_product_attribute)- return [product_to_assignedproductattributes[product_id] for product_id in keys]--class AssignedVariantAttributesByProductVariantId(DataLoader):context_key = "assignedvariantattributes_by_productvariant"@@ -193,33 +140,6 @@ class AssignedVariantAttributesByProductVariantId(DataLoader):return [variant_attributes[variant_id] for variant_id in keys]-class AttributeValuesByAssignedProductAttributeIdLoader(DataLoader):- context_key = "attributevalues_by_assignedproductattribute"-- def batch_load(self, keys):- attribute_values = list(- AssignedProductAttributeValue.objects.using(self.database_connection_name)- .filter(assignment_id__in=keys)- .iterator()- )- value_ids = [a.value_id for a in attribute_values]-- def map_assignment_to_values(values):- value_map = dict(zip(value_ids, values))- assigned_product_map = defaultdict(list)- for attribute_value in attribute_values:- assigned_product_map[attribute_value.assignment_id].append(- value_map.get(attribute_value.value_id)- )- return [assigned_product_map[key] for key in keys]-- return (- AttributeValueByIdLoader(self.context)- .load_many(value_ids)- .then(map_assignment_to_values)- )--class AttributeValuesByAssignedVariantAttributeIdLoader(DataLoader):context_key = "attributevalues_by_assignedvariantattribute"@@ -247,85 +167,69 @@ class AttributeValuesByAssignedVariantAttributeIdLoader(DataLoader):)-class SelectedAttributesByProductIdLoader(DataLoader):- context_key = "selectedattributes_by_product"+class AttributeValuesByProductIdLoader(DataLoader):+ context_key = "attributevalues_by_productid"def batch_load(self, keys):- def with_products_and_assigned_attributes(result):- products, product_attributes = result- products = [product for product in products if product is not None]- assigned_product_attribute_ids = [- a.id for attrs in product_attributes for a in attrs- ]- product_type_ids = list({p.product_type_id for p in products})- product_attributes = dict(zip(keys, product_attributes))+ # Using list + iterator is a small optimisation because iterator causes+ # the db to not store the whole resultset into the memory+ # https://docs.djangoproject.com/en/3.2/ref/models/querysets/#iterator+ attribute_values = list(+ AssignedProductAttributeValue.objects.using(self.database_connection_name)+ .filter(product_id__in=keys)+ .iterator()+ )+ value_ids = [a.value_id for a in attribute_values]- def with_attributeproducts_and_values(result):- attribute_products, attribute_values = result- attribute_ids = list(- {ap.attribute_id for aps in attribute_products for ap in aps}- )- attribute_products = dict(zip(product_type_ids, attribute_products))- attribute_values = dict(- zip(assigned_product_attribute_ids, attribute_values)+ def with_products(products):+ products = [product for product in products if product]+ product_type_ids = [p.product_type_id for p in products]++ def with_attributes_and_values(result):+ attribute_products, values = result+ product_type_attrubutes = dict(+ zip(product_type_ids, attribute_products))+ values_by_id_map = dict(zip(value_ids, values))+ assigned_product_map = defaultdict(list)++ for product in products:+ product_values = [+ values_by_id_map.get(product_value.value_id)+ for product_value in attribute_values+ if product_value.product_id == product.id+ ]- def with_attributes(attributes):- id_to_attribute = dict(zip(attribute_ids, attributes))- selected_attributes_map = defaultdict(list)- for key, product in zip(keys, products):- assigned_producttype_attributes = attribute_products[- product.product_type_id+ attributes = product_type_attrubutes[product.product_type_id]+ for attribute_tuple in attributes:+ attribute = attribute_tuple[0]+ values = [+ value+ for value in product_values+ if value and value.attribute_id == attribute.id]- assigned_product_attributes = product_attributes[key]- for (- assigned_producttype_attribute- ) in assigned_producttype_attributes:- product_assignment = next(- (- apa- for apa in assigned_product_attributes- if apa.assignment_id- == assigned_producttype_attribute.id- ),- None,- )- attribute = id_to_attribute[- assigned_producttype_attribute.attribute_id- ]- if product_assignment:- values = attribute_values[product_assignment.id]- else:- values = []- selected_attributes_map[key].append(- {"values": values, "attribute": attribute}- )- return [selected_attributes_map[key] for key in keys]+ assigned_product_map[product.id].append(+ {+ "attribute": attribute,+ "values": values,+ }+ )+ return [assigned_product_map[key] for key in keys]++ attributes = ProductAttributesByProductTypeIdLoader(self.context).load_many(+ product_type_ids+ )+ values = AttributeValueByIdLoader(self.context).load_many(value_ids)+ return Promise.all([attributes, values]).then(with_attributes_and_values)- return (- AttributesByAttributeId(self.context)- .load_many(attribute_ids)- .then(with_attributes)- )+ return ProductByIdLoader(self.context).load_many(keys).then(with_products)- attribute_products = AttributeProductsByProductTypeIdLoader(- self.context- ).load_many(product_type_ids)- attribute_values = AttributeValuesByAssignedProductAttributeIdLoader(- self.context- ).load_many(assigned_product_attribute_ids)- return Promise.all([attribute_products, attribute_values]).then(- with_attributeproducts_and_values- )- products = ProductByIdLoader(self.context).load_many(keys)- assigned_attributes = AssignedProductAttributesByProductIdLoader(- self.context- ).load_many(keys)+class SelectedAttributesByProductIdLoader(DataLoader):+ context_key = "selectedattributes_by_product"- return Promise.all([products, assigned_attributes]).then(- with_products_and_assigned_attributes- )+ def batch_load(self, product_ids):+ return AttributeValuesByProductIdLoader(self.context).load_many(product_ids)class SelectedAttributesByProductVariantIdLoader(DataLoader):diff --git a/saleor/graphql/product/filters.py b/saleor/graphql/product/filters.pyindex a4b8e9ea7a..dda871ab58 100644--- a/saleor/graphql/product/filters.py+++ b/saleor/graphql/product/filters.py@@ -14,7 +14,6 @@ from django.utils import timezonefrom ...attribute import AttributeInputTypefrom ...attribute.models import (- AssignedProductAttribute,AssignedProductAttributeValue,AssignedVariantAttribute,AssignedVariantAttributeValue,@@ -219,13 +218,8 @@ def filter_products_by_attributes_values(qs, queries: T_PRODUCT_FILTER_QUERIES):assigned_product_attribute_values = (AssignedProductAttributeValue.objects.filter(value_id__in=values))- assigned_product_attributes = AssignedProductAttribute.objects.filter(- Exists(- assigned_product_attribute_values.filter(assignment_id=OuterRef("pk"))- )- )product_attribute_filter = Q(- Exists(assigned_product_attributes.filter(product_id=OuterRef("pk")))+ Exists(assigned_product_attribute_values.filter(product_id=OuterRef("pk"))))assigned_variant_attribute_values = (@@ -252,11 +246,8 @@ def filter_products_by_attributes_values_qs(qs, values_qs):assigned_product_attribute_values = AssignedProductAttributeValue.objects.filter(value__in=values_qs)- assigned_product_attributes = AssignedProductAttribute.objects.filter(- Exists(assigned_product_attribute_values.filter(assignment_id=OuterRef("pk")))- )product_attribute_filter = Q(- Exists(assigned_product_attributes.filter(product_id=OuterRef("pk")))+ Exists(assigned_product_attribute_values.filter(product_id=OuterRef("pk"))))assigned_variant_attribute_values = AssignedVariantAttributeValue.objects.filter(diff --git a/saleor/graphql/product/mutations/attributes.py b/saleor/graphql/product/mutations/attributes.pyindex 0ac5e56b56..a76340277e 100644--- a/saleor/graphql/product/mutations/attributes.py+++ b/saleor/graphql/product/mutations/attributes.py@@ -645,11 +645,40 @@ class ProductReorderAttributeValues(BaseReorderAttributeValuesMutation):description="The list of reordering operations for given attribute values.",)+ @classmethod+ def perform(+ cls,+ instance_id: str,+ instance_type: str,+ data: dict,+ assignment_lookup: str,+ error_code_enum,+ ):+ attribute_id = data["attribute_id"]+ moves = data["moves"]++ instance = cls.get_instance(instance_id)+ cls.validate_attribute_assignment(+ instance, instance_type, attribute_id, error_code_enum+ )+ values_m2m = getattr(instance, assignment_lookup)++ try:+ operations = cls.prepare_operations(moves, values_m2m)+ except ValidationError as error:+ error.code = error_code_enum.NOT_FOUND.value+ raise ValidationError({"moves": error})++ with traced_atomic_transaction():+ perform_reordering(values_m2m, operations)++ return instance+@classmethoddef perform_mutation(cls, _root, _info: ResolveInfo, /, **data):product_id = data["product_id"]product = cls.perform(- product_id, "product", data, "productvalueassignment", ProductErrorCode+ product_id, "product", data, "attributevalues", ProductErrorCode)return ProductReorderAttributeValues(@@ -675,6 +704,31 @@ class ProductReorderAttributeValues(BaseReorderAttributeValuesMutation):)return product+ @classmethod+ def validate_attribute_assignment(+ cls, instance, instance_type, attribute_id: str, error_code_enum+ ):+ """Validate if this attribute_id is assigned to this product."""+ attribute_pk = cls.get_global_id_or_error(+ attribute_id, only_type=Attribute, field="attribute_id"+ )++ attribute_assignment = attribute_models.AttributeProduct.objects.filter(+ attribute_id=attribute_pk, product_type_id=instance.product_type_id+ ).exists()++ if not attribute_assignment:+ raise ValidationError(+ {+ "attribute_id": ValidationError(+ f"Couldn't resolve to a {instance_type} "+ f"attribute: {attribute_id}.",+ code=error_code_enum.NOT_FOUND.value,+ )+ }+ )+ return attribute_assignment+class ProductVariantReorderAttributeValues(BaseReorderAttributeValuesMutation):product_variant = graphene.Field(diff --git a/saleor/graphql/product/mutations/product/product_create.py b/saleor/graphql/product/mutations/product/product_create.pyindex 65ea1737c8..6a360abd28 100644--- a/saleor/graphql/product/mutations/product/product_create.py+++ b/saleor/graphql/product/mutations/product/product_create.py@@ -9,7 +9,7 @@ from .....product import modelsfrom .....product.error_codes import ProductErrorCodefrom .....product.tasks import update_products_discounted_prices_for_promotion_taskfrom ....attribute.types import AttributeValueInput-from ....attribute.utils import AttributeAssignmentMixin, AttrValuesInput+from ....attribute.utils import AttrValuesInput, ProductAttributeAssignmentMixinfrom ....channel import ChannelContextfrom ....core import ResolveInfofrom ....core.descriptions import (@@ -144,7 +144,9 @@ class ProductCreate(ModelMutation):cls, attributes: dict, product_type: models.ProductType) -> T_INPUT_MAP:attributes_qs = product_type.product_attributes.all()- attributes = AttributeAssignmentMixin.clean_input(attributes, attributes_qs)+ attributes = ProductAttributeAssignmentMixin.clean_input(+ attributes, attributes_qs+ )return attributes@classmethod@@ -207,7 +209,7 @@ class ProductCreate(ModelMutation):instance.save()attributes = cleaned_input.get("attributes")if attributes:- AttributeAssignmentMixin.save(instance, attributes)+ ProductAttributeAssignmentMixin.save(instance, attributes)@classmethoddef _save_m2m(cls, _info: ResolveInfo, instance, cleaned_data):diff --git a/saleor/graphql/product/mutations/product/product_delete.py b/saleor/graphql/product/mutations/product/product_delete.pyindex 3c6a987dfe..073863a381 100644--- a/saleor/graphql/product/mutations/product/product_delete.py+++ b/saleor/graphql/product/mutations/product/product_delete.py@@ -1,4 +1,5 @@import graphene+from django.db.models.expressions import Exists, OuterReffrom .....attribute import AttributeInputTypefrom .....attribute import models as attribute_models@@ -82,7 +83,14 @@ class ProductDelete(ModelDeleteMutation, ModelWithExtRefMutation):@staticmethoddef delete_assigned_attribute_values(instance):+ assigned_values = attribute_models.AssignedProductAttributeValue.objects.filter(+ product_id=instance.pk+ )+ attributes = attribute_models.Attribute.objects.filter(+ input_type__in=AttributeInputType.TYPES_WITH_UNIQUE_VALUES+ )+attribute_models.AttributeValue.objects.filter(- productassignments__product_id=instance.id,- attribute__input_type__in=AttributeInputType.TYPES_WITH_UNIQUE_VALUES,+ Exists(assigned_values.filter(value_id=OuterRef("id"))),+ Exists(attributes.filter(id=OuterRef("attribute_id"))),).delete()diff --git a/saleor/graphql/product/mutations/product/product_update.py b/saleor/graphql/product/mutations/product/product_update.pyindex 9e563dddc1..5f74a8a90b 100644--- a/saleor/graphql/product/mutations/product/product_update.py+++ b/saleor/graphql/product/mutations/product/product_update.py@@ -4,7 +4,7 @@ from .....attribute import models as attribute_modelsfrom .....permission.enums import ProductPermissionsfrom .....product import modelsfrom .....product.tasks import update_products_discounted_prices_for_promotion_task-from ....attribute.utils import AttributeAssignmentMixin, AttrValuesInput+from ....attribute.utils import AttrValuesInput, ProductAttributeAssignmentMixinfrom ....core import ResolveInfofrom ....core.descriptions import ADDED_IN_310from ....core.mutations import ModelWithExtRefMutation@@ -42,7 +42,7 @@ class ProductUpdate(ProductCreate, ModelWithExtRefMutation):cls, attributes: dict, product_type: models.ProductType) -> T_INPUT_MAP:attributes_qs = product_type.product_attributes.all()- attributes = AttributeAssignmentMixin.clean_input(+ attributes = ProductAttributeAssignmentMixin.clean_input(attributes, attributes_qs, creation=False)return attributes@@ -62,7 +62,7 @@ class ProductUpdate(ProductCreate, ModelWithExtRefMutation):# prefetch them.object_id = cls.get_object_id(**data)if object_id and data.get("attributes"):- # Prefetches needed by AttributeAssignmentMixin and+ # Prefetches needed by ProductAttributeAssignmentMixin and# associate_attribute_values_to_instanceqs = cls.Meta.model.objects.prefetch_related("product_type__product_attributes__values",diff --git a/saleor/graphql/product/mutations/product_type/product_type_delete.py b/saleor/graphql/product/mutations/product_type/product_type_delete.pyindex 14baee6c0f..0ac8e59515 100644--- a/saleor/graphql/product/mutations/product_type/product_type_delete.py+++ b/saleor/graphql/product/mutations/product_type/product_type_delete.py@@ -1,5 +1,6 @@import graphenefrom django.db.models import Q+from django.db.models.expressions import Exists, OuterReffrom .....attribute import AttributeInputTypefrom .....attribute import models as attribute_models@@ -56,10 +57,16 @@ class ProductTypeDelete(ModelDeleteMutation):@staticmethoddef delete_assigned_attribute_values(instance_pk):+ attributes = attribute_models.Attribute.objects.filter(+ input_type__in=AttributeInputType.TYPES_WITH_UNIQUE_VALUES+ )+ assigned_values = attribute_models.AssignedProductAttributeValue.objects.filter(+ product__product_type_id=instance_pk+ )attribute_models.AttributeValue.objects.filter(- Q(attribute__input_type__in=AttributeInputType.TYPES_WITH_UNIQUE_VALUES)- & (- Q(productassignments__assignment__product_type_id=instance_pk)+ Exists(attributes.filter(id=OuterRef("attribute_id"))),+ (+ Q(Exists(assigned_values.filter(value_id=OuterRef("id"))))| Q(variantassignments__assignment__product_type_id=instance_pk)- )+ ),).delete()diff --git a/saleor/graphql/product/tests/benchmark/test_product.py b/saleor/graphql/product/tests/benchmark/test_product.pyindex 28fe84ee2b..ebe9fb2f79 100644--- a/saleor/graphql/product/tests/benchmark/test_product.py+++ b/saleor/graphql/product/tests/benchmark/test_product.py@@ -4,6 +4,10 @@ import grapheneimport pytestfrom graphene import Node+from .....attribute.tests.model_helpers import (+ get_product_attribute_values,+ get_product_attributes,+)from .....attribute.utils import associate_attribute_values_to_instancefrom .....core.taxes import TaxTypefrom .....plugins.manager import PluginsManager@@ -580,14 +584,12 @@ def test_filter_products_by_attributes(api_client, product_list, channel_USD, count_queries):product = product_list[0]- attr_assignment = product.attributes.first()- attr = attr_assignment.attribute+ attr = get_product_attributes(product).first()+ first_assigned_value = get_product_attribute_values(product, attr).first()variables = {"channel": channel_USD.slug,"filter": {- "attributes": [- {"slug": attr.slug, "values": [attr_assignment.values.first().slug]}- ]+ "attributes": [{"slug": attr.slug, "values": [first_assigned_value.slug]}]},}get_graphql_content(api_client.post_graphql(QUERY_PRODUCTS_WITH_FILTER, variables))diff --git a/saleor/graphql/product/tests/mutations/test_product_bulk_create.py b/saleor/graphql/product/tests/mutations/test_product_bulk_create.pyindex 00c0e56a14..18dc756fd5 100644--- a/saleor/graphql/product/tests/mutations/test_product_bulk_create.py+++ b/saleor/graphql/product/tests/mutations/test_product_bulk_create.py@@ -8,6 +8,10 @@ import grapheneimport pytestimport pytz+from .....attribute.tests.model_helpers import (+ get_product_attribute_values,+ get_product_attributes,+)from .....product.error_codes import ProductBulkCreateErrorCodefrom .....product.models import Productfrom .....product.tests.utils import create_image@@ -583,8 +587,6 @@ def test_product_bulk_create_with_attributes(size_attribute,description_json,permission_manage_products,- media_root,- channel_USD,):# givendescription_json = json.dumps(description_json)@@ -664,10 +666,10 @@ def test_product_bulk_create_with_attributes()for product in products:- first_attribute_assignment = product.attributes.first()- assert product.attributes.count() == 2- assert first_attribute_assignment.attribute == color_attr- assert first_attribute_assignment.values.count() == 1+ product_attributes = get_product_attributes(product)+ assert len(product_attributes) == 2+ assert product_attributes[0] == color_attr+ assert get_product_attribute_values(product, color_attr).count() == 1def test_product_bulk_create_with_attributes_using_external_refs(@@ -738,10 +740,11 @@ def test_product_bulk_create_with_attributes_using_external_refs()for product in products:- first_attribute_assignment = product.attributes.first()- assert product.attributes.count() == 2- assert first_attribute_assignment.attribute == color_attr- assert first_attribute_assignment.values.count() == 1+ attributes = get_product_attributes(product)+ first_attribute_assignment = attributes[0]+ assert len(attributes) == 2+ assert first_attribute_assignment == color_attr+ assert get_product_attribute_values(product, color_attr).count() == 1def test_product_bulk_create_with_attributes_and_create_new_value_with_external_ref(@@ -811,10 +814,11 @@ def test_product_bulk_create_with_attributes_and_create_new_value_with_external_== color_attr.slug)assert color_attr.values.count() == color_attr_values_count + 1- first_attribute_assignment = product.attributes.first()- assert product.attributes.count() == 1- assert first_attribute_assignment.attribute == color_attr- assert first_attribute_assignment.values.count() == 1+ attributes = get_product_attributes(product)+ first_attribute_assignment = attributes[0]+ assert len(attributes) == 1+ assert first_attribute_assignment == color_attr+ assert get_product_attribute_values(product, color_attr).count() == 1def test_product_bulk_create_return_error_when_attribute_id_and_external_ref_provided(diff --git a/saleor/graphql/product/tests/mutations/test_product_update.py b/saleor/graphql/product/tests/mutations/test_product_update.pyindex 54165ce6df..6d36af7692 100644--- a/saleor/graphql/product/tests/mutations/test_product_update.py+++ b/saleor/graphql/product/tests/mutations/test_product_update.py@@ -9,8 +9,18 @@ from django.utils.text import slugifyfrom freezegun import freeze_timefrom .....attribute import AttributeInputType-from .....attribute.models import Attribute, AttributeValue-from .....attribute.utils import associate_attribute_values_to_instance+from .....attribute.models import (+ AssignedProductAttributeValue,+ Attribute,+ AttributeValue,+)+from .....attribute.tests.model_helpers import (+ get_product_attribute_values,+ get_product_attributes,+)+from .....attribute.utils import (+ associate_attribute_values_to_instance,+)from .....core.taxes import TaxTypefrom .....graphql.core.enums import AttributeErrorCodefrom .....graphql.tests.utils import get_graphql_content@@ -577,11 +587,13 @@ def test_update_product_with_file_attribute_value_new_value_is_not_created(product_id = graphene.Node.to_global_id("Product", product.pk)attribute_id = graphene.Node.to_global_id("Attribute", file_attribute.pk)+product_type.product_attributes.add(file_attribute)- existing_value = file_attribute.values.first()+ attribute_values = file_attribute.values.all()+ existing_value = attribute_values[0]associate_attribute_values_to_instance(product, file_attribute, existing_value)- values_count = file_attribute.values.count()+ values_count = len(attribute_values)domain = site_settings.site.domainfile_url = f"http://{domain}{settings.MEDIA_URL}{existing_value.file_url}"@@ -762,8 +774,7 @@ def test_update_product_clear_attribute_values(product_id = graphene.Node.to_global_id("Product", product.pk)- product_attr = product.attributes.first()- attribute = product_attr.assignment.attribute+ attribute = get_product_attributes(product).first()attribute.value_required = Falseattribute.save(update_fields=["value_required"])@@ -788,8 +799,7 @@ def test_update_product_clear_attribute_values(assert len(attributes) == 1assert not attributes[0]["values"]- with pytest.raises(product_attr._meta.model.DoesNotExist):- product_attr.refresh_from_db()+ assert not get_product_attribute_values(product, attribute).exists()updated_webhook_mock.assert_called_once_with(product)@@ -812,8 +822,8 @@ def test_update_product_clean_boolean_attribute_value(product, boolean_attribute, boolean_attribute.values.first())- product_attr = product.attributes.get(assignment__attribute_id=boolean_attribute.id)- assert product_attr.values.count() == 1+ product_attr = get_product_attributes(product).get(id=boolean_attribute.id)+ assert get_product_attribute_values(product, product_attr).count() == 1variables = {"productId": product_id,@@ -837,7 +847,7 @@ def test_update_product_clean_boolean_attribute_value("values": [],}assert expected_att_data in attributes- assert product_attr.values.count() == 0+ assert get_product_attribute_values(product, product_attr).count() == 0def test_update_product_clean_file_attribute_value(@@ -858,8 +868,8 @@ def test_update_product_clean_file_attribute_value(product, file_attribute, file_attribute.values.first())- product_attr = product.attributes.get(assignment__attribute_id=file_attribute.id)- assert product_attr.values.count() == 1+ product_attr = get_product_attributes(product).get(pk=file_attribute.id)+ assert get_product_attribute_values(product, product_attr).count() == 1variables = {"productId": product_id,@@ -883,7 +893,7 @@ def test_update_product_clean_file_attribute_value("values": [],}assert expected_att_data in attributes- assert product_attr.values.count() == 0+ assert get_product_attribute_values(product, file_attribute).count() == 0@patch("saleor.plugins.manager.PluginsManager.product_updated")@@ -899,8 +909,7 @@ def test_update_product_none_as_attribute_values(product_id = graphene.Node.to_global_id("Product", product.pk)- product_attr = product.attributes.first()- attribute = product_attr.assignment.attribute+ attribute = get_product_attributes(product).first()attribute.value_required = Falseattribute.save(update_fields=["value_required"])@@ -925,8 +934,7 @@ def test_update_product_none_as_attribute_values(assert len(attributes) == 1assert not attributes[0]["values"]- with pytest.raises(product_attr._meta.model.DoesNotExist):- product_attr.refresh_from_db()+ assert not get_product_attribute_values(product, attribute).exists()updated_webhook_mock.assert_called_once_with(product)@@ -1712,10 +1720,11 @@ def test_update_product_change_values_ordering(product, product_type_page_reference_attribute, attr_value_2, attr_value_1)+ attribute = get_product_attributes(product).first()assert list(- product.attributes.first().productvalueassignment.values_list(- "value_id", flat=True- )+ AssignedProductAttributeValue.objects.filter(+ value__attribute_id=attribute.id, product_id=product.id+ ).values_list("value_id", flat=True)) == [attr_value_2.pk, attr_value_1.pk]variables = {@@ -1753,10 +1762,12 @@ def test_update_product_change_values_ordering(for val in [attr_value_1, attr_value_2]]product.refresh_from_db()++ attribute = get_product_attributes(product).first()assert list(- product.attributes.first().productvalueassignment.values_list(- "value_id", flat=True- )+ AssignedProductAttributeValue.objects.filter(+ value__attribute_id=attribute.id, product_id=product.id+ ).values_list("value_id", flat=True)) == [attr_value_1.pk, attr_value_2.pk]updated_webhook_mock.assert_called_once_with(product)@@ -2498,7 +2509,7 @@ def test_update_product_with_multiselect_attribute_non_existing_values(product = product_with_multiple_values_attributesproduct_id = graphene.Node.to_global_id("Product", product.pk)- attribute = product.attributes.first().attribute+ attribute = get_product_attributes(product).first()attribute_id = graphene.Node.to_global_id("Attribute", attribute.pk)value_count = AttributeValue.objects.count()@@ -2548,17 +2559,21 @@ def test_update_product_with_multiselect_attribute_existing_values(product = product_with_multiple_values_attributesproduct_id = graphene.Node.to_global_id("Product", product.pk)- attribute = product.attributes.first().attribute+ attribute = get_product_attributes(product).first()+ assert attribute is not Noneattribute_id = graphene.Node.to_global_id("Attribute", attribute.pk)- attr_value_1 = product.attributes.first().values.all()[0]+ attribute_values = get_product_attribute_values(product, attribute)+ attr_value_1 = attribute_values[0]attr_value_id_1 = graphene.Node.to_global_id("AttributeValue", attr_value_1.pk)- attr_value_name_1 = product.attributes.first().values.all()[0].name- attr_value_2 = product.attributes.first().values.all()[1]+ attr_value_name_1 = attr_value_1.name+ attr_value_2 = attribute_values[1]attr_value_id_2 = graphene.Node.to_global_id("AttributeValue", attr_value_2.pk)- attr_value_name_2 = product.attributes.first().values.all()[1].name+ attr_value_name_2 = attr_value_2.nameassociate_attribute_values_to_instance(product, attribute, attr_value_1)- assert len(product.attributes.first().values.all()) == 1++ attribute = get_product_attributes(product).first()+ assert len(get_product_attribute_values(product, attribute)) == 1variables = {"productId": product_id,@@ -2596,25 +2611,28 @@ def test_update_product_with_multiselect_attribute_new_values_not_created(staff_api_client,product_with_multiple_values_attributes,permission_manage_products,- site_settings,):# givenquery = MUTATION_UPDATE_PRODUCTproduct = product_with_multiple_values_attributesproduct_id = graphene.Node.to_global_id("Product", product.pk)- attribute = product.attributes.first().attribute+ attribute = get_product_attributes(product).first()+ assert attribute is not Noneattribute_id = graphene.Node.to_global_id("Attribute", attribute.pk)- attr_value_1 = product.attributes.first().values.all()[0]+ attr_values = get_product_attribute_values(product, attribute)++ attr_value_1 = attr_values[0]attr_value_id_1 = graphene.Node.to_global_id("AttributeValue", attr_value_1.pk)- attr_value_name_1 = product.attributes.first().values.all()[0].name- attr_value_2 = product.attributes.first().values.all()[1]+ attr_value_name_1 = attr_value_1.name++ attr_value_2 = attr_values[1]attr_value_id_2 = graphene.Node.to_global_id("AttributeValue", attr_value_2.pk)- attr_value_name_2 = product.attributes.first().values.all()[1].name+ attr_value_name_2 = attr_value_2.namevalue_count = AttributeValue.objects.count()- assert len(product.attributes.first().values.all()) == 2+ assert len(attr_values) == 2variables = {"productId": product_id,@@ -2806,9 +2824,9 @@ def test_update_product_with_multiselect_attribute_by_both_id_and_value(product = product_with_multiple_values_attributesproduct_id = graphene.Node.to_global_id("Product", product.pk)- attribute = product.attributes.first().attribute+ attribute = get_product_attributes(product).first()attribute_id = graphene.Node.to_global_id("Attribute", attribute.pk)- attr_value = product.attributes.first().values.all()[0]+ attr_value = get_product_attributes(product).first().values.all()[0]attr_value_id = graphene.Node.to_global_id("AttributeValue", attr_value.pk)variables = {@@ -2842,16 +2860,15 @@ def test_update_product_with_multiselect_attribute_by_id_duplicated(staff_api_client,product_with_multiple_values_attributes,permission_manage_products,- site_settings,):# givenquery = MUTATION_UPDATE_PRODUCTproduct = product_with_multiple_values_attributesproduct_id = graphene.Node.to_global_id("Product", product.pk)- attribute = product.attributes.first().attribute+ attribute = get_product_attributes(product).first()attribute_id = graphene.Node.to_global_id("Attribute", attribute.pk)- attr_value = product.attributes.first().values.all()[0]+ attr_value = get_product_attributes(product).first().values.all()[0]attr_value_id = graphene.Node.to_global_id("AttributeValue", attr_value.pk)variables = {@@ -2885,16 +2902,15 @@ def test_update_product_with_multiselect_attribute_by_name_duplicated(staff_api_client,product_with_multiple_values_attributes,permission_manage_products,- site_settings,):# givenquery = MUTATION_UPDATE_PRODUCTproduct = product_with_multiple_values_attributesproduct_id = graphene.Node.to_global_id("Product", product.pk)- attribute = product.attributes.first().attribute+ attribute = get_product_attributes(product).first()attribute_id = graphene.Node.to_global_id("Attribute", attribute.pk)- attr_value_name = product.attributes.first().values.all()[0].name+ attr_value_name = get_product_attributes(product).first().values.all()[0].namevariables = {"productId": product_id,diff --git a/saleor/graphql/product/tests/queries/test_products_query.py b/saleor/graphql/product/tests/queries/test_products_query.pyindex a93db37191..691942d2bb 100644--- a/saleor/graphql/product/tests/queries/test_products_query.py+++ b/saleor/graphql/product/tests/queries/test_products_query.py@@ -5,6 +5,7 @@ import grapheneimport pytestfrom django.utils.dateparse import parse_datetime+from .....attribute.tests.model_helpers import get_product_attributesfrom .....core.postgres import FlatConcatSearchVectorfrom .....product.models import (Product,@@ -1190,7 +1191,7 @@ def test_products_with_variants_query_as_app(}"""product = product_with_multiple_values_attributes- attribute = product.attributes.first().attribute+ attribute = get_product_attributes(product).first()attribute.visible_in_storefront = Falseattribute.save()second_product = productdiff --git a/saleor/graphql/product/tests/queries/test_products_query_with_filter.py b/saleor/graphql/product/tests/queries/test_products_query_with_filter.pyindex d56a233f55..5dfc9ab076 100644--- a/saleor/graphql/product/tests/queries/test_products_query_with_filter.py+++ b/saleor/graphql/product/tests/queries/test_products_query_with_filter.py@@ -8,6 +8,10 @@ from django.utils import timezonefrom .....attribute import AttributeInputType, AttributeTypefrom .....attribute.models import Attribute, AttributeValue+from .....attribute.tests.model_helpers import (+ get_product_attribute_values,+ get_product_attributes,+)from .....attribute.utils import associate_attribute_values_to_instancefrom .....core.postgres import FlatConcatSearchVectorfrom .....core.units import MeasurementUnits@@ -259,8 +263,8 @@ def test_products_query_with_filter_by_attributes_values_and_range(numeric_attribute,permission_manage_products,):- product_attr = product.attributes.first()- attr_value_1 = product_attr.values.first()+ product_attr = get_product_attributes(product).first()+ attr_value_1 = get_product_attribute_values(product, product_attr).first()product.product_type.product_attributes.add(numeric_attribute)associate_attribute_values_to_instance(product, numeric_attribute, *numeric_attribute.values.all()diff --git a/saleor/graphql/product/tests/queries/test_products_query_with_where.py b/saleor/graphql/product/tests/queries/test_products_query_with_where.pyindex 3fd5a9f2fc..a1d197fb5b 100644--- a/saleor/graphql/product/tests/queries/test_products_query_with_where.py+++ b/saleor/graphql/product/tests/queries/test_products_query_with_where.py@@ -5,6 +5,10 @@ import pytestfrom django.utils import timezonefrom .....attribute.models import Attribute, AttributeValue+from .....attribute.tests.model_helpers import (+ get_product_attribute_values,+ get_product_attributes,+)from .....attribute.utils import associate_attribute_values_to_instancefrom .....product import ProductTypeKindfrom .....product.models import Product, ProductChannelListing, ProductType@@ -859,8 +863,9 @@ def test_products_filter_by_attributes_values_and_range(channel_USD,):# given- product_attr = product_list[0].attributes.first()- attr_value_1 = product_attr.values.first()+ product = product_list[0]+ product_attr = get_product_attributes(product).first()+ attr_value_1 = get_product_attribute_values(product, product_attr).first()product_list[0].product_type.product_attributes.add(numeric_attribute)associate_attribute_values_to_instance(product_list[0], numeric_attribute, *numeric_attribute.values.all()diff --git a/saleor/graphql/product/tests/test_attributes.py b/saleor/graphql/product/tests/test_attributes.pyindex 33acdedd75..02bf42a382 100644--- a/saleor/graphql/product/tests/test_attributes.py+++ b/saleor/graphql/product/tests/test_attributes.py@@ -5,11 +5,16 @@ import pytestfrom ....attribute import AttributeInputType, AttributeTypefrom ....attribute.models import (+ AssignedProductAttributeValue,Attribute,AttributeProduct,AttributeValue,AttributeVariant,)+from ....attribute.tests.model_helpers import (+ get_product_attribute_values,+ get_product_attributes,+)from ....attribute.utils import associate_attribute_values_to_instancefrom ....product import ProductTypeKindfrom ....product.error_codes import ProductErrorCode@@ -72,7 +77,7 @@ def test_resolve_attributes_with_hidden(product_attribute = color_attributevariant_attribute = size_attribute- expected_product_attribute_count = product.attributes.count() - 1+ expected_product_attribute_count = get_product_attributes(product).count() - 1expected_variant_attribute_count = variant.attributes.count() - 1if is_staff:@@ -102,11 +107,12 @@ def test_resolve_attribute_values(user_api_client, product, staff_user, channel_variant = product.variants.first()- assert product.attributes.count() == 1+ assert get_product_attributes(product).count() == 1assert variant.attributes.count() == 1+ attribute = get_product_attributes(product).first()product_attribute_values = list(- product.attributes.first().values.values_list("slug", flat=True)+ get_product_attribute_values(product, attribute).values_list("slug", flat=True))variant_attribute_values = list(variant.attributes.first().values.values_list("slug", flat=True)@@ -173,10 +179,16 @@ def test_resolve_attribute_values_non_assigned_to_node(attribute=unassigned_product_attribute, product_type=product_type, sort_order=0)AttributeVariant.objects.create(- attribute=unassigned_variant_attribute, product_type=product_type, sort_order=0+ attribute=unassigned_variant_attribute,+ product_type=product_type,+ sort_order=0,)- assert product.attributes.count() == 1+ # All attributes assigned for the same product type should be returned+ assert get_product_attributes(product).count() == 2++ # no additional values should be added+ assert product.attributevalues.count() == 1assert variant.attributes.count() == 1product = get_graphql_content(api_client.post_graphql(query, variables))["data"][@@ -204,7 +216,7 @@ def test_resolve_assigned_attribute_without_values(variant = product.variants.get()# Remove all attributes and values from the product and its variant- product.attributesrelated.clear()+ AssignedProductAttributeValue.objects.filter(product_id=product.pk).delete()variant.attributesrelated.clear()# Retrieve the product and variant's attributes@@ -1325,6 +1337,7 @@ def test_sort_product_attribute_values(staff_api_client.user.user_permissions.add(permission_manage_products)product_type = product.product_type+product_type.product_attributes.clear()product_type.product_attributes.add(product_type_page_reference_attribute)diff --git a/saleor/graphql/translations/tests/test_translations.py b/saleor/graphql/translations/tests/test_translations.pyindex 7fa633c39e..44f434881c 100644--- a/saleor/graphql/translations/tests/test_translations.py+++ b/saleor/graphql/translations/tests/test_translations.py@@ -7,6 +7,10 @@ import pytestfrom django.utils.functional import SimpleLazyObjectfrom freezegun import freeze_time+from ....attribute.tests.model_helpers import (+ get_product_attribute_values,+ get_product_attributes,+)from ....attribute.utils import associate_attribute_values_to_instancefrom ....discount.error_codes import DiscountErrorCodefrom ....permission.models import Permission@@ -2158,8 +2162,9 @@ def test_rich_text_attribute_value_create_translation(permission_manage_translations,):# given- assigned_attribute = product_with_rich_text_attribute[0].attributes.first()- attribute_value = assigned_attribute.attribute.values.first()+ product = product_with_rich_text_attribute[0]+ assigned_attribute = get_product_attributes(product).first()+ attribute_value = get_product_attribute_values(product, assigned_attribute).first()attribute_value_id = graphene.Node.to_global_id("AttributeValue", attribute_value.id)@@ -2289,8 +2294,9 @@ def test_rich_text_attribute_value_update_translation_only_rich_text(# givenbase_text = "Base Text"rich_text = dummy_editorjs(base_text)- assigned_attribute = product_with_rich_text_attribute[0].attributes.first()- attribute_value = assigned_attribute.attribute.values.first()+ product = product_with_rich_text_attribute[0]+ assigned_attribute = get_product_attributes(product).first()+ attribute_value = get_product_attribute_values(product, assigned_attribute).first()attribute_value.translations.create(language_code="pl", name=base_text, rich_text=rich_text)@@ -2325,8 +2331,9 @@ def test_rich_text_attribute_value_update_translation_only_rich_text_long_text(# givenbase_text = "Base Text"rich_text = dummy_editorjs(base_text)- assigned_attribute = product_with_rich_text_attribute[0].attributes.first()- attribute_value = assigned_attribute.attribute.values.first()+ product = product_with_rich_text_attribute[0]+ assigned_attribute = get_product_attributes(product).first()+ attribute_value = get_product_attribute_values(product, assigned_attribute).first()attribute_value.translations.create(language_code="pl", name=base_text, rich_text=rich_text)@@ -2363,8 +2370,9 @@ def test_rich_text_attribute_value_update_translation_only_rich_text_name_set_ma# givenbase_text = "Base Text"rich_text = dummy_editorjs(base_text)- assigned_attribute = product_with_rich_text_attribute[0].attributes.first()- attribute_value = assigned_attribute.attribute.values.first()+ product = product_with_rich_text_attribute[0]+ assigned_attribute = get_product_attributes(product).first()+ attribute_value = get_product_attribute_values(product, assigned_attribute).first()attribute_value.translations.create(language_code="pl", name=base_text, rich_text=rich_text)@@ -2400,8 +2408,9 @@ def test_rich_text_attribute_value_update_translation_only_rich_text_empty_name(# givenbase_text = "Base Text"rich_text = dummy_editorjs(base_text)- assigned_attribute = product_with_rich_text_attribute[0].attributes.first()- attribute_value = assigned_attribute.attribute.values.first()+ product = product_with_rich_text_attribute[0]+ assigned_attribute = get_product_attributes(product).first()+ attribute_value = get_product_attribute_values(product, assigned_attribute).first()attribute_value.translations.create(language_code="pl", name=base_text, rich_text=rich_text)@@ -2436,8 +2445,9 @@ def test_rich_text_attribute_value_update_translation_only_rich_text_name_null(# givenbase_text = "Base Text"rich_text = dummy_editorjs(base_text)- assigned_attribute = product_with_rich_text_attribute[0].attributes.first()- attribute_value = assigned_attribute.attribute.values.first()+ product = product_with_rich_text_attribute[0]+ assigned_attribute = get_product_attributes(product).first()+ attribute_value = get_product_attribute_values(product, assigned_attribute).first()attribute_value.translations.create(language_code="pl", name=base_text, rich_text=rich_text)@@ -3690,8 +3700,7 @@ def test_product_and_attribute_translation(user_api_client, product, channel_USDproduct.translations.create(language_code="pl", name="Produkt", description=description)- assigned_attribute = product.attributes.first()- attribute = assigned_attribute.attribute+ attribute = get_product_attributes(product).first()attribute.translations.create(language_code="pl", name="Kolor")query = """@@ -3779,8 +3788,9 @@ def test_product_attribute_value_rich_text_translation():# givenrich_text = dummy_editorjs("Test_dummy_data")- assigned_attribute = product_with_rich_text_attribute[0].attributes.first()- attribute_value = assigned_attribute.attribute.values.first()+ product = product_with_rich_text_attribute[0]+ assigned_attribute = get_product_attributes(product).first()+ attribute_value = get_product_attribute_values(product, assigned_attribute).first()attribute_value.translations.create(language_code="pl", rich_text=rich_text)product_id = graphene.Node.to_global_id(diff --git a/saleor/order/notifications.py b/saleor/order/notifications.pyindex 647e916f15..5e88d2c100 100644--- a/saleor/order/notifications.py+++ b/saleor/order/notifications.py@@ -1,3 +1,4 @@+from collections import defaultdictfrom collections.abc import Iterablefrom decimal import Decimalfrom typing import TYPE_CHECKING, Optional@@ -46,16 +47,23 @@ def get_default_images_payload(images: list[ProductMedia]):return {"first_image": first_image_payload, "images": images_payload}-def get_product_attributes(product):- attributes = product.attributes.all()+def get_product_attributes_payload(product):+ attribute_products = product.product_type.attributeproduct.all()+ assigned_values = product.attributevalues.all()++ values_map = defaultdict(list)+ for av in assigned_values:+ values_map[av.value.attribute_id].append(av.value)+attributes_payload = []- for attr in attributes:+ for attribute_product in attribute_products:+ attr = attribute_product.attributeattributes_payload.append({"assignment": {"attribute": {- "slug": attr.assignment.attribute.slug,- "name": attr.assignment.attribute.name,+ "slug": attr.slug,+ "name": attr.name,}},"values": [@@ -65,7 +73,7 @@ def get_product_attributes(product):"slug": value.slug,"file_url": value.file_url,}- for value in attr.values.all()+ for value in values_map[attr.id]],})@@ -77,7 +85,7 @@ def get_product_payload(product: Product):images = [media for media in all_media if media.type == ProductMediaTypes.IMAGE]return {"id": to_global_id_or_none(product),- "attributes": get_product_attributes(product),+ "attributes": get_product_attributes_payload(product),"weight": str(product.weight or ""),**get_default_images_payload(images),}@@ -239,10 +247,13 @@ def get_default_order_payload(order: "Order", redirect_url: str = ""):tax = order.total_gross_amount - order.total_net_amount or Decimal(0)lines = order.lines.prefetch_related(- "variant__product__media","variant__media",- "variant__product__attributes__assignment__attribute",- "variant__product__attributes__values",+ "variant__product__media",+ "variant__product__attributevalues",+ "variant__product__attributevalues__value",+ "variant__product__product_type",+ "variant__product__product_type__attributeproduct",+ "variant__product__product_type__attributeproduct__attribute",).all()currency = order.currencyquantize_price_fields(order, fields=ORDER_PRICE_FIELDS, currency=currency)diff --git a/saleor/order/tests/test_notifications.py b/saleor/order/tests/test_notifications.pyindex 6ab5f9fb62..ae1ecda724 100644--- a/saleor/order/tests/test_notifications.py+++ b/saleor/order/tests/test_notifications.py@@ -7,6 +7,10 @@ from django.core.files import Filefrom measurement.measures import Weightfrom prices import Money, fixed_discount+from ...attribute.tests.model_helpers import (+ get_product_attribute_values,+ get_product_attributes,+)from ...core.notify_events import NotifyEventTypefrom ...core.prices import quantize_pricefrom ...core.tests.utils import get_site_context_payload@@ -96,20 +100,21 @@ def test_get_custom_order_payload(order, site_settings):def test_get_order_line_payload(order_line):- order_line.variant.product.weight = Weight(kg=5)- order_line.variant.product.save()+ product = order_line.variant.product+ product.weight = Weight(kg=5)+ product.save()payload = get_order_line_payload(order_line)- attributes = order_line.variant.product.attributes.all()+ attributes = get_product_attributes(product)expected_attributes_payload = []for attr in attributes:expected_attributes_payload.append({"assignment": {"attribute": {- "slug": attr.assignment.attribute.slug,- "name": attr.assignment.attribute.name,+ "slug": attr.slug,+ "name": attr.name,}},"values": [@@ -119,7 +124,7 @@ def test_get_order_line_payload(order_line):"slug": value.slug,"file_url": value.file_url,}- for value in attr.values.all()+ for value in get_product_attribute_values(product, attr)],})diff --git a/saleor/product/managers.py b/saleor/product/managers.pyindex 015959c608..177558076a 100644--- a/saleor/product/managers.py+++ b/saleor/product/managers.py@@ -12,7 +12,6 @@ from django.db.models import (Exists,ExpressionWrapper,F,- FilteredRelation,OuterRef,Q,Subquery,@@ -132,7 +131,11 @@ class ProductsQueryset(models.QuerySet):to sort by.:param descending: The sorting direction."""- from ..attribute.models import AttributeProduct, AttributeValue+ from ..attribute.models import (+ AssignedProductAttributeValue,+ AttributeProduct,+ AttributeValue,+ )qs: models.QuerySet = self# If the passed attribute ID is valid, execute the sorting@@ -144,69 +147,52 @@ class ProductsQueryset(models.QuerySet):concatenated_values=Value(None, output_field=models.CharField()),)- # Retrieve all the products' attribute data IDs (assignments) and- # product types that have the given attribute associated to them- associated_values = tuple(- AttributeProduct.objects.filter(attribute_id=attribute_pk).values_list(- "pk", "product_type_id"- )- )-- if not associated_values:- qs = qs.annotate(- concatenated_values_order=Value(- None, output_field=models.IntegerField()- ),- concatenated_values=Value(None, output_field=models.CharField()),- )-- else:- attribute_associations, product_types_associated_to_attribute = zip(- *associated_values- )-- qs = qs.annotate(- # Contains to retrieve the attribute data (singular) of each product- # Refer to `AttributeProduct`.- filtered_attribute=FilteredRelation(- relation_name="attributes",- condition=Q(attributes__assignment_id__in=attribute_associations),- ),- # Implicit `GROUP BY` required for the `StringAgg` aggregation- grouped_ids=Count("id"),- # String aggregation of the attribute's values to efficiently sort them- concatenated_values=Case(- # If the product has no association data but has- # the given attribute associated to its product type,- # then consider the concatenated values as empty (non-null).- When(- Q(product_type_id__in=product_types_associated_to_attribute)- & Q(filtered_attribute=None),- then=models.Value(""),- ),- default=StringAgg(- F("filtered_attribute__values__name"),- delimiter=",",- ordering=(- [- f"filtered_attribute__values__{field_name}"- for field_name in AttributeValue._meta.ordering or []- ]- ),+ qs = qs.annotate(+ # Implicit `GROUP BY` required for the `StringAgg` aggregation+ grouped_ids=Count("id"),+ # String aggregation of the attribute's values to efficiently sort them+ concatenated_values=Case(+ # If the product has no association data but has+ # the given attribute associated to its product type,+ # then consider the concatenated values as empty (non-null).+ When(+ Exists(+ AttributeProduct.objects.filter(+ product_type_id=OuterRef("product_type_id"),+ attribute_id=attribute_pk,+ )+ )+ & ~Exists(+ AssignedProductAttributeValue.objects.filter(+ product_id=OuterRef("id"), value__attribute_id=attribute_pk+ )),- output_field=models.CharField(),+ then=Value(""),),- concatenated_values_order=Case(- # Make the products having no such attribute be last in the sorting- When(concatenated_values=None, then=2),- # Put the products having an empty attribute value at the bottom of- # the other products.- When(concatenated_values="", then=1),- # Put the products having an attribute value to be always at the top- default=0,- output_field=models.IntegerField(),+ default=StringAgg(+ F("attributevalues__value__name"),+ filter=Q(attributevalues__value__attribute_id=attribute_pk),+ delimiter=",",+ ordering=(+ [+ f"attributevalues__value__{field_name}"+ for field_name in AttributeValue._meta.ordering or []+ ]+ ),),- )+ output_field=models.CharField(),+ ),+ concatenated_values_order=Case(+ # Make the products having no such attribute be last in the sorting+ When(concatenated_values=None, then=2),+ # Put the products having an empty attribute value at the bottom of+ # the other products.+ When(concatenated_values="", then=1),+ # Put the products having an attribute value to be always at the top+ default=0,+ output_field=models.IntegerField(),+ ),+ )# Sort by concatenated_values_order then# Sort each group of products (0, 1, 2, ...) per attribute values@@ -221,8 +207,6 @@ class ProductsQueryset(models.QuerySet):def prefetched_for_webhook(self, single_object=True):common_fields = (- "attributes__values",- "attributes__assignment__attribute","media","variants__attributes__values","variants__attributes__assignment__attribute",@@ -230,6 +214,8 @@ class ProductsQueryset(models.QuerySet):"variants__stocks__allocations","variants__channel_listings__channel","channel_listings__channel",+ "product_type__product_attributes__values",+ "product_type__attributeproduct",)if single_object:return self.prefetch_related(*common_fields)diff --git a/saleor/product/search.py b/saleor/product/search.pyindex c5f68923b0..c763cb675f 100644--- a/saleor/product/search.py+++ b/saleor/product/search.py@@ -1,10 +1,17 @@-from typing import TYPE_CHECKING+from collections import defaultdict+from typing import TYPE_CHECKING, Unionfrom django.conf import settingsfrom django.contrib.postgres.search import SearchQuery, SearchRankfrom django.db.models import F, Q, Value, prefetch_related_objects+from django.db.models.expressions import Exists, OuterReffrom ..attribute import AttributeInputType+from ..attribute.models import (+ AssignedProductAttributeValue,+ Attribute,+ AttributeProduct,+)from ..core.postgres import FlatConcatSearchVector, NoValidationSearchVectorfrom ..core.utils.editorjs import clean_editor_jsfrom .models import Product@@ -15,9 +22,9 @@ if TYPE_CHECKING:PRODUCT_SEARCH_FIELDS = ["name", "description_plaintext"]PRODUCT_FIELDS_TO_PREFETCH = ["variants__attributes__values",- "variants__attributes__assignment__attribute",- "attributes__values",- "attributes__assignment__attribute",+ "variants__attributes",+ "attributevalues__value",+ "product_type__attributeproduct__attribute",]PRODUCTS_BATCH_SIZE = 300@@ -58,13 +65,14 @@ def prepare_product_search_vector_value() -> list[NoValidationSearchVector]:if not already_prefetched:prefetch_related_objects([product], *PRODUCT_FIELDS_TO_PREFETCH)+search_vectors = [NoValidationSearchVector(Value(product.name), config="simple", weight="A"),NoValidationSearchVector(Value(product.description_plaintext), config="simple", weight="C"),*generate_attributes_search_vector_value(- product.attributes.all()[: settings.PRODUCT_MAX_INDEXED_ATTRIBUTES]+ product,),*generate_variants_search_vector_value(product),]@@ -87,13 +95,49 @@ def generate_variants_search_vector_value(]if search_vectors:for variant in variants:- search_vectors += generate_attributes_search_vector_value(+ search_vectors += generate_attributes_search_vector_value_with_assignment(variant.attributes.all()[: settings.PRODUCT_MAX_INDEXED_ATTRIBUTES])return search_vectorsdef generate_attributes_search_vector_value(+ product: "Product",+) -> list[NoValidationSearchVector]:+ """Prepare `search_vector` value for assigned attributes.++ Method should receive assigned attributes with prefetched `values`+ """+ product_attributes = AttributeProduct.objects.filter(+ product_type_id=product.product_type_id+ )+ attributes = Attribute.objects.filter(+ Exists(product_attributes.filter(attribute_id=OuterRef("id")))+ ).order_by("attributeproduct__sort_order")[+ : settings.PRODUCT_MAX_INDEXED_ATTRIBUTES+ ]++ assigned_values = AssignedProductAttributeValue.objects.filter(+ product_id=product.pk+ )+ prefetch_related_objects(assigned_values, "value")++ search_vectors = []++ values_map = defaultdict(list)+ for av in assigned_values:+ values_map[av.value.attribute_id].append(av.value)++ for attribute in attributes:+ values = values_map[attribute.pk][+ : settings.PRODUCT_MAX_INDEXED_ATTRIBUTE_VALUES+ ]++ search_vectors += get_search_vectors_for_values(attribute, values)+ return search_vectors+++def generate_attributes_search_vector_value_with_assignment(assigned_attributes: "QuerySet",) -> list[NoValidationSearchVector]:"""Prepare `search_vector` value for assigned attributes.@@ -104,51 +148,59 @@ def generate_attributes_search_vector_value(search_vectors = []for assigned_attribute in assigned_attributes:attribute = assigned_attribute.assignment.attribute-- input_type = attribute.input_typevalues = assigned_attribute.values.all()[: settings.PRODUCT_MAX_INDEXED_ATTRIBUTE_VALUES]- if input_type in [AttributeInputType.DROPDOWN, AttributeInputType.MULTISELECT]:- search_vectors += [- NoValidationSearchVector(Value(value.name), config="simple", weight="B")- for value in values- ]- elif input_type == AttributeInputType.RICH_TEXT:- search_vectors += [- NoValidationSearchVector(- Value(clean_editor_js(value.rich_text, to_string=True)),- config="simple",- weight="B",- )- for value in values- ]- elif input_type == AttributeInputType.PLAIN_TEXT:- search_vectors += [- NoValidationSearchVector(- Value(value.plain_text), config="simple", weight="B"- )- for value in values- ]- elif input_type == AttributeInputType.NUMERIC:- unit = attribute.unit- search_vectors += [- NoValidationSearchVector(- Value(value.name + " " + unit if unit else value.name),- config="simple",- weight="B",- )- for value in values- ]- elif input_type in [AttributeInputType.DATE, AttributeInputType.DATE_TIME]:- search_vectors += [- NoValidationSearchVector(- Value(value.date_time.strftime("%Y-%m-%d %H:%M:%S")),- config="simple",- weight="B",- )- for value in values- ]+ search_vectors += get_search_vectors_for_values(attribute, values)+ return search_vectors+++def get_search_vectors_for_values(+ attribute: Attribute, values: Union[list, "QuerySet"]+) -> list[NoValidationSearchVector]:+ search_vectors = []++ input_type = attribute.input_type+ if input_type in [AttributeInputType.DROPDOWN, AttributeInputType.MULTISELECT]:+ search_vectors += [+ NoValidationSearchVector(Value(value.name), config="simple", weight="B")+ for value in values+ ]+ elif input_type == AttributeInputType.RICH_TEXT:+ search_vectors += [+ NoValidationSearchVector(+ Value(clean_editor_js(value.rich_text, to_string=True)),+ config="simple",+ weight="B",+ )+ for value in values+ ]+ elif input_type == AttributeInputType.PLAIN_TEXT:+ search_vectors += [+ NoValidationSearchVector(+ Value(value.plain_text), config="simple", weight="B"+ )+ for value in values+ ]+ elif input_type == AttributeInputType.NUMERIC:+ unit = attribute.unit+ search_vectors += [+ NoValidationSearchVector(+ Value(value.name + " " + unit if unit else value.name),+ config="simple",+ weight="B",+ )+ for value in values+ ]+ elif input_type in [AttributeInputType.DATE, AttributeInputType.DATE_TIME]:+ search_vectors += [+ NoValidationSearchVector(+ Value(value.date_time.strftime("%Y-%m-%d %H:%M:%S")),+ config="simple",+ weight="B",+ )+ for value in values+ ]return search_vectorsdiff --git a/saleor/static/populatedb_data.json b/saleor/static/populatedb_data.jsonindex 6c949ac692..47db61140e 100644--- a/saleor/static/populatedb_data.json+++ b/saleor/static/populatedb_data.json@@ -7437,182 +7437,92 @@{"model": "attribute.assignedproductattributevalue","pk": 193,- "fields": { "sort_order": 0, "value": 138, "assignment": 37 }+ "fields": { "sort_order": 0, "value": 138, "product": 126 }},{"model": "attribute.assignedproductattributevalue","pk": 194,- "fields": { "sort_order": 0, "value": 105, "assignment": 38 }+ "fields": { "sort_order": 0, "value": 105, "product": 131 }},{"model": "attribute.assignedproductattributevalue","pk": 195,- "fields": { "sort_order": 0, "value": 107, "assignment": 39 }+ "fields": { "sort_order": 0, "value": 107, "product": 132 }},{"model": "attribute.assignedproductattributevalue","pk": 196,- "fields": { "sort_order": 0, "value": 105, "assignment": 40 }+ "fields": { "sort_order": 0, "value": 105, "product": 133 }},{"model": "attribute.assignedproductattributevalue","pk": 197,- "fields": { "sort_order": 0, "value": 105, "assignment": 41 }+ "fields": { "sort_order": 0, "value": 105, "product": 134 }},{"model": "attribute.assignedproductattributevalue","pk": 198,- "fields": { "sort_order": 0, "value": 106, "assignment": 42 }+ "fields": { "sort_order": 0, "value": 106, "product": 135 }},{"model": "attribute.assignedproductattributevalue","pk": 199,- "fields": { "sort_order": 0, "value": 105, "assignment": 43 }+ "fields": { "sort_order": 0, "value": 105, "product": 136 }},{"model": "attribute.assignedproductattributevalue","pk": 200,- "fields": { "sort_order": 0, "value": 105, "assignment": 44 }+ "fields": { "sort_order": 0, "value": 105, "product": 137 }},{"model": "attribute.assignedproductattributevalue","pk": 201,- "fields": { "sort_order": 0, "value": 105, "assignment": 45 }+ "fields": { "sort_order": 0, "value": 105, "product": 138 }},{"model": "attribute.assignedproductattributevalue","pk": 204,- "fields": { "sort_order": 0, "value": 105, "assignment": 48 }+ "fields": { "sort_order": 0, "value": 105, "product": 141 }},{"model": "attribute.assignedproductattributevalue","pk": 206,- "fields": { "sort_order": 0, "value": 140, "assignment": 50 }+ "fields": { "sort_order": 0, "value": 140, "product": 143 }},{"model": "attribute.assignedproductattributevalue","pk": 207,- "fields": { "sort_order": 0, "value": 141, "assignment": 51 }+ "fields": { "sort_order": 0, "value": 141, "product": 146 }},{"model": "attribute.assignedproductattributevalue","pk": 208,- "fields": { "sort_order": 0, "value": 141, "assignment": 52 }+ "fields": { "sort_order": 0, "value": 141, "product": 147 }},{"model": "attribute.assignedproductattributevalue","pk": 210,- "fields": { "sort_order": 0, "value": 129, "assignment": 54 }+ "fields": { "sort_order": 0, "value": 129, "product": 152 }},{"model": "attribute.assignedproductattributevalue","pk": 211,- "fields": { "sort_order": 0, "value": 123, "assignment": 55 }+ "fields": { "sort_order": 0, "value": 123, "product": 153 }},{"model": "attribute.assignedproductattributevalue","pk": 212,- "fields": { "sort_order": 0, "value": 122, "assignment": 56 }+ "fields": { "sort_order": 0, "value": 122, "product": 154 }},{"model": "attribute.assignedproductattributevalue","pk": 213,- "fields": { "sort_order": 0, "value": 124, "assignment": 57 }+ "fields": { "sort_order": 0, "value": 124, "product": 155 }},{"model": "attribute.assignedproductattributevalue","pk": 214,- "fields": { "sort_order": 0, "value": 105, "assignment": 58 }- },- {- "model": "attribute.assignedproductattribute",- "pk": 37,- "fields": { "product": 126, "assignment": 10 }- },- {- "model": "attribute.assignedproductattribute",- "pk": 38,- "fields": { "product": 131, "assignment": 11 }- },- {- "model": "attribute.assignedproductattribute",- "pk": 39,- "fields": { "product": 132, "assignment": 11 }- },- {- "model": "attribute.assignedproductattribute",- "pk": 40,- "fields": { "product": 133, "assignment": 11 }- },- {- "model": "attribute.assignedproductattribute",- "pk": 41,- "fields": { "product": 134, "assignment": 12 }- },- {- "model": "attribute.assignedproductattribute",- "pk": 42,- "fields": { "product": 135, "assignment": 12 }- },- {- "model": "attribute.assignedproductattribute",- "pk": 43,- "fields": { "product": 136, "assignment": 12 }- },- {- "model": "attribute.assignedproductattribute",- "pk": 44,- "fields": { "product": 137, "assignment": 12 }- },- {- "model": "attribute.assignedproductattribute",- "pk": 45,- "fields": { "product": 138, "assignment": 12 }- },- {- "model": "attribute.assignedproductattribute",- "pk": 48,- "fields": { "product": 141, "assignment": 13 }- },- {- "model": "attribute.assignedproductattribute",- "pk": 50,- "fields": { "product": 143, "assignment": 13 }- },- {- "model": "attribute.assignedproductattribute",- "pk": 51,- "fields": { "product": 146, "assignment": 10 }- },- {- "model": "attribute.assignedproductattribute",- "pk": 52,- "fields": { "product": 147, "assignment": 10 }- },- {- "model": "attribute.assignedproductattribute",- "pk": 54,- "fields": { "product": 152, "assignment": 14 }- },- {- "model": "attribute.assignedproductattribute",- "pk": 55,- "fields": { "product": 153, "assignment": 14 }- },- {- "model": "attribute.assignedproductattribute",- "pk": 56,- "fields": { "product": 154, "assignment": 14 }- },- {- "model": "attribute.assignedproductattribute",- "pk": 57,- "fields": { "product": 155, "assignment": 14 }- },- {- "model": "attribute.assignedproductattribute",- "pk": 58,- "fields": { "product": 161, "assignment": 12 }+ "fields": { "sort_order": 0, "value": 105, "product": 161 }},{"model": "attribute.attributeproduct",diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.pyindex e2163faf81..db4dd7a6b2 100644--- a/saleor/tests/fixtures.py+++ b/saleor/tests/fixtures.py@@ -3090,7 +3090,7 @@ def product_with_variant_with_file_attribute(@pytest.fixture-def product_with_multiple_values_attributes(product, product_type, category) -> Product:+def product_with_multiple_values_attributes(product, product_type) -> Product:attribute = Attribute.objects.create(slug="modes",name="Available Modes",diff --git a/saleor/webhook/payloads.py b/saleor/webhook/payloads.pyindex 7f3dcb2ce3..967597b94d 100644--- a/saleor/webhook/payloads.py+++ b/saleor/webhook/payloads.py@@ -50,7 +50,8 @@ from .payload_serializers import PayloadSerializerfrom .serializers import (serialize_checkout_lines,serialize_checkout_lines_for_tax_calculation,- serialize_product_or_variant_attributes,+ serialize_product_attributes,+ serialize_variant_attributes,)if TYPE_CHECKING:@@ -724,7 +725,7 @@ def generate_product_payload(},extra_dict_data={"meta": generate_meta(requestor_data=generate_requestor(requestor)),- "attributes": serialize_product_or_variant_attributes(product),+ "attributes": serialize_product_attributes(product),"media": [{"alt": media_obj.alt,@@ -840,7 +841,7 @@ def generate_product_variant_payload():extra_dict_data = {"id": lambda v: v.get_global_id(),- "attributes": lambda v: serialize_product_or_variant_attributes(v),+ "attributes": lambda v: serialize_variant_attributes(v),"product_id": lambda v: graphene.Node.to_global_id("Product", v.product_id),"media": lambda v: generate_product_variant_media_payload(v),"channel_listings": lambda v: json.loads(@@ -1130,7 +1131,13 @@ def generate_sample_payload(event_name: str) -> Optional[dict]:payload = generate_customer_payload(user)elif event_name == WebhookEventAsyncType.PRODUCT_CREATED:product = _get_sample_object(- Product.objects.prefetch_related("category", "collections", "variants")+ Product.objects.prefetch_related(+ "category",+ "collections",+ "variants",+ "attributevalues__value",+ "product_type__attributeproduct__attribute",+ ))payload = generate_product_payload(product) if product else Noneelif event_name in checkout_events:diff --git a/saleor/webhook/serializers.py b/saleor/webhook/serializers.pyindex 3409178200..67a710d946 100644--- a/saleor/webhook/serializers.py+++ b/saleor/webhook/serializers.py@@ -1,3 +1,4 @@+from collections import defaultdictfrom collections.abc import Iterablefrom datetime import date, datetimefrom decimal import Decimal@@ -54,7 +55,7 @@ def serialize_checkout_lines(checkout: "Checkout") -> list[dict]:"full_name": variant.display_product(),"product_name": product.name,"variant_name": variant.name,- "attributes": serialize_product_or_variant_attributes(variant),+ "attributes": serialize_variant_attributes(variant),})return data@@ -104,9 +105,72 @@ def serialize_checkout_lines_for_tax_calculation(]-def serialize_product_or_variant_attributes(- product_or_variant: Union["Product", "ProductVariant"]-) -> list[dict]:+def serialize_product_attributes(product: "Product") -> list[dict]:+ data = []++ def _prepare_reference(attribute, attr_value):+ if attribute.input_type != AttributeInputType.REFERENCE:+ return+ if attribute.entity_type == AttributeEntityType.PAGE:+ reference_pk = attr_value.reference_page_id+ elif attribute.entity_type == AttributeEntityType.PRODUCT:+ reference_pk = attr_value.reference_product_id+ else:+ return None++ reference_id = graphene.Node.to_global_id(attribute.entity_type, reference_pk)+ return reference_id++ attribute_products = product.product_type.attributeproduct.all()+ assigned_values = product.attributevalues.all()++ values_map = defaultdict(list)+ for av in assigned_values:+ values_map[av.value.attribute_id].append(av.value)++ for attribute_product in attribute_products:+ attribute = attribute_product.attribute # type: ignore[attr-defined]++ attr_id = graphene.Node.to_global_id("Attribute", attribute.pk)+ attr_data: dict[Any, Any] = {+ "name": attribute.name,+ "input_type": attribute.input_type,+ "slug": attribute.slug,+ "entity_type": attribute.entity_type,+ "unit": attribute.unit,+ "id": attr_id,+ "values": [],+ }++ for attr_value in values_map[attribute.pk]:+ attr_slug = attr_value.slug+ value: dict[+ str, Optional[Union[str, datetime, date, bool, dict[str, Any]]]+ ] = {+ "name": attr_value.name,+ "slug": attr_slug,+ "value": attr_value.value,+ "rich_text": attr_value.rich_text,+ "boolean": attr_value.boolean,+ "date_time": attr_value.date_time,+ "date": attr_value.date_time,+ "reference": _prepare_reference(attribute, attr_value),+ "file": None,+ }++ if attr_value.file_url:+ value["file"] = {+ "content_type": attr_value.content_type,+ "file_url": attr_value.file_url,+ }+ attr_data["values"].append(value)++ data.append(attr_data)++ return data+++def serialize_variant_attributes(variant: "ProductVariant") -> list[dict]:data = []def _prepare_reference(attribute, attr_value):@@ -122,7 +186,7 @@ def serialize_product_or_variant_attributes(reference_id = graphene.Node.to_global_id(attribute.entity_type, reference_pk)return reference_id- for attr in product_or_variant.attributes.all():+ for attr in variant.attributes.all():attr_id = graphene.Node.to_global_id("Attribute", attr.assignment.attribute_id)attribute = attr.assignment.attributeattr_data: dict[Any, Any] = {diff --git a/saleor/webhook/tests/test_webhook_serializers.py b/saleor/webhook/tests/test_webhook_serializers.pyindex 6168d098f4..f42bcd374e 100644--- a/saleor/webhook/tests/test_webhook_serializers.py+++ b/saleor/webhook/tests/test_webhook_serializers.py@@ -1,9 +1,11 @@-from operator import itemgetterfrom unittest.mock import ANY, sentinelimport grapheneimport pytest+from ...attribute import AttributeEntityType, AttributeInputType, AttributeType+from ...attribute.models import Attribute, AttributeValue+from ...attribute.utils import associate_attribute_values_to_instancefrom ...checkout import base_calculationsfrom ...checkout.fetch import fetch_checkout_info, fetch_checkout_linesfrom ...core.prices import quantize_price@@ -17,19 +19,15 @@ from ...product.utils.variant_prices import update_discounted_prices_for_promotifrom ..serializers import (serialize_checkout_lines,serialize_checkout_lines_for_tax_calculation,- serialize_product_or_variant_attributes,+ serialize_product_attributes,+ serialize_variant_attributes,)-def test_serialize_product_attributes(- product_with_variant_with_two_attributes, product_with_multiple_values_attributes-):- variant_data = serialize_product_or_variant_attributes(+def test_serialize_variant_attributes(product_with_variant_with_two_attributes):+ variant_data = serialize_variant_attributes(product_with_variant_with_two_attributes.variants.first())- product_data = serialize_product_or_variant_attributes(- product_with_multiple_values_attributes- )assert len(variant_data) == 2assert variant_data[1] == {"entity_type": None,@@ -53,32 +51,143 @@ def test_serialize_product_attributes(],}- assert len(product_data) == 1- assert product_data[0]["name"] == "Available Modes"- assert sorted(product_data[0]["values"], key=itemgetter("name")) == [- {- "name": "Eco Mode",- "slug": "eco",- "file": None,- "reference": None,- "rich_text": None,- "date_time": None,- "date": None,- "boolean": None,- "value": "",- },- {- "name": "Performance Mode",- "slug": "power",- "file": None,- "reference": None,- "rich_text": None,- "date_time": None,- "date": None,- "boolean": None,- "value": "",- },- ]++def test_serialize_product_attributes(+ product,+ product_type,+ product_type_product_reference_attribute,+ product_type_page_reference_attribute,+ file_attribute,+ page,+):+ # given+ multiselect_name = "Available Modes"+ attribute = Attribute.objects.create(+ slug="modes",+ name=multiselect_name,+ input_type=AttributeInputType.MULTISELECT,+ type=AttributeType.PRODUCT_TYPE,+ )+ product_type.product_attributes.set(+ [+ attribute,+ product_type_product_reference_attribute,+ product_type_page_reference_attribute,+ file_attribute,+ ]+ )++ # multiselect+ attr_val_1 = AttributeValue.objects.create(+ attribute=attribute, name="Eco Mode", slug="eco"+ )+ associate_attribute_values_to_instance(product, attribute, attr_val_1)++ # product reference+ product_slug = f"{product.pk}"+ attr_value = AttributeValue.objects.create(+ attribute=product_type_product_reference_attribute,+ name=product.name,+ slug=product_slug,+ reference_product=product,+ )+ associate_attribute_values_to_instance(+ product, product_type_product_reference_attribute, attr_value+ )++ # page reference+ page_slug = f"{page.pk}"+ ref_value = AttributeValue.objects.create(+ attribute=product_type_page_reference_attribute,+ reference_page=page,+ slug=page_slug,+ name=page.title,+ date_time=None,+ )+ associate_attribute_values_to_instance(+ product, product_type_page_reference_attribute, ref_value+ )++ # file+ file_attr_value = file_attribute.values.first()+ associate_attribute_values_to_instance(product, file_attribute, file_attr_value)++ # when+ product_data = serialize_product_attributes(product)++ # then+ assert len(product_data) == 4+ for data in product_data:+ if data["name"] == multiselect_name:+ assert data["values"] == [+ {+ "name": "Eco Mode",+ "slug": "eco",+ "file": None,+ "reference": None,+ "rich_text": None,+ "date_time": None,+ "date": None,+ "boolean": None,+ "value": "",+ },+ ]+ continue++ if data["name"] == product_type_product_reference_attribute.name:+ assert data["values"] == [+ {+ "name": product.name,+ "slug": product_slug,+ "file": None,+ "reference": graphene.Node.to_global_id(+ AttributeEntityType.PRODUCT, product.pk+ ),+ "rich_text": None,+ "date_time": None,+ "date": None,+ "boolean": None,+ "value": "",+ },+ ]+ continue++ if data["name"] == product_type_page_reference_attribute.name:+ assert data["values"] == [+ {+ "name": page.title,+ "slug": page_slug,+ "file": None,+ "reference": graphene.Node.to_global_id(+ AttributeEntityType.PAGE, page.pk+ ),+ "rich_text": None,+ "date_time": None,+ "date": None,+ "boolean": None,+ "value": "",+ },+ ]+ continue++ if data["name"] == file_attribute.name:+ assert data["values"] == [+ {+ "name": file_attr_value.name,+ "slug": file_attr_value.slug,+ "file": {+ "content_type": file_attr_value.content_type,+ "file_url": file_attr_value.file_url,+ },+ "reference": None,+ "rich_text": None,+ "date_time": None,+ "date": None,+ "boolean": None,+ "value": "",+ },+ ]+ continueATTRIBUTES = sentinel.ATTRIBUTES@@ -113,7 +222,7 @@ def test_serialize_checkout_lines("full_name": variant.display_product(),"product_name": product.name,"variant_name": variant.name,- "attributes": serialize_product_or_variant_attributes(variant),+ "attributes": serialize_variant_attributes(variant),"variant_id": variant.get_global_id(),}assert len(checkout_lines_data) == len(list(checkout_lines))@@ -152,7 +261,7 @@ def test_serialize_checkout_lines_with_promotion(checkout_with_item_on_promotion"full_name": variant.display_product(),"product_name": product.name,"variant_name": variant.name,- "attributes": serialize_product_or_variant_attributes(variant),+ "attributes": serialize_variant_attributes(variant),"variant_id": variant.get_global_id(),}assert len(checkout_lines_data) == len(list(checkout_lines))