Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Simplify Page <> Attribute relation
Michał Macioszczyk3dd2ea531238
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 455d49672d..9cc4cf62f3 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -29,6 +29,7 @@ All notable, unreleased changes to this project will be documented in this file.- Add transaction items deletion to cleardb command. - #14198 by @jakubkuc- 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# 3.17.0diff --git a/saleor/attribute/migrations/0037_remove_assignedpageattribute.py b/saleor/attribute/migrations/0037_remove_assignedpageattribute.pynew file mode 100644index 0000000000..4b800ba0d3--- /dev/null+++ b/saleor/attribute/migrations/0037_remove_assignedpageattribute.py@@ -0,0 +1,94 @@+# Generated by Django 3.2.20 on 2023-07-25 15:58++import django.db.models.deletion+from django.db import migrations, models+++class Migration(migrations.Migration):+ dependencies = [+ ("attribute", "0036_assignedproductattributevalue_product_data_migration"),+ ]++ state_operations = [+ migrations.AlterField(+ model_name="assignedpageattributevalue",+ name="page",+ field=models.ForeignKey(+ db_index=False,+ null=False,+ blank=False,+ on_delete=django.db.models.deletion.CASCADE,+ related_name="attributevalues",+ to="page.page",+ ),+ ),+ migrations.RemoveField(+ model_name="attributepage",+ name="assigned_pages",+ ),+ migrations.AlterUniqueTogether(+ name="assignedpageattributevalue",+ unique_together={("value", "page")},+ ),+ migrations.RemoveField(+ model_name="assignedpageattributevalue",+ name="assignment",+ ),+ migrations.DeleteModel(+ name="AssignedPageAttribute",+ ),+ ]++ operations = [+ migrations.AlterField(+ model_name="assignedpageattributevalue",+ name="assignment",+ field=models.ForeignKey(+ on_delete=django.db.models.deletion.SET_NULL,+ related_name="pagevalueassignment",+ to="attribute.AssignedPageAttribute",+ null=True,+ ),+ ),+ migrations.AlterField(+ model_name="assignedpageattribute",+ name="page",+ field=models.ForeignKey(+ on_delete=django.db.models.deletion.SET_NULL,+ related_name="attributes",+ to="page.Page",+ null=True,+ ),+ ),+ migrations.AlterField(+ model_name="assignedpageattribute",+ name="assignment",+ field=models.ForeignKey(+ on_delete=django.db.models.deletion.SET_NULL,+ related_name="pageassignments",+ to="attribute.AttributePage",+ null=True,+ ),+ ),+ # Remove FK constraints so that the DB doesn't try to truncate the references+ migrations.RunSQL(+ """+ ALTER TABLE attribute_assignedpageattribute+ DROP CONSTRAINT IF EXISTS+ attribute_assignedpa_assignment_id_db2b2662_fk_attribute;++ ALTER TABLE attribute_assignedpageattribute+ DROP CONSTRAINT IF EXISTS+ attribute_assignedpa_page_id_6db6dc92_fk_page_page;++ ALTER TABLE attribute_assignedpageattributevalue+ DROP CONSTRAINT IF EXISTS+ attribute_assignedpa_assignment_id_6863be0a_fk_attribute;++ ALTER TABLE attribute_assignedpageattributevalue+ DROP CONSTRAINT IF EXISTS+ attribute_assignedpageat_value_id_assignment_id_f51f07e4_uniq;+ """+ ),+ migrations.SeparateDatabaseAndState(state_operations=state_operations),+ ]diff --git a/saleor/attribute/models/__init__.py b/saleor/attribute/models/__init__.pyindex d7b1f64844..7f6bd3cfee 100644--- a/saleor/attribute/models/__init__.py+++ b/saleor/attribute/models/__init__.py@@ -4,7 +4,7 @@ from .base import (AttributeValue,AttributeValueTranslation,)-from .page import AssignedPageAttribute, AssignedPageAttributeValue, AttributePage+from .page import AssignedPageAttributeValue, AttributePagefrom .product import (AssignedProductAttribute,AssignedProductAttributeValue,@@ -21,7 +21,6 @@ __all__ = ["AttributeTranslation","AttributeValue","AttributeValueTranslation",- "AssignedPageAttribute","AssignedPageAttributeValue","AttributePage","AssignedProductAttribute",diff --git a/saleor/attribute/models/base.py b/saleor/attribute/models/base.pyindex 354c84f492..67e49a1a6f 100644--- a/saleor/attribute/models/base.py+++ b/saleor/attribute/models/base.py@@ -320,7 +320,7 @@ class AttributeValueTranslation(Translation):if assigned_page_attribute_value := (attribute_value.pagevalueassignment.first()):- if page := assigned_page_attribute_value.assignment.page:+ if page := assigned_page_attribute_value.page:context["page_id"] = page.idif page_type_id := page.page_type_id:context["page_type_id"] = page_type_iddiff --git a/saleor/attribute/models/page.py b/saleor/attribute/models/page.pyindex cb58cd5190..a85bdbdd7d 100644--- a/saleor/attribute/models/page.py+++ b/saleor/attribute/models/page.py@@ -3,7 +3,11 @@ from django.db import modelsfrom ...core.models import SortableModelfrom ...page.models import Page, PageType+<<<<<<< HEADfrom .base import AssociatedAttributeManager, AttributeValue, BaseAssignedAttribute+=======+from .base import AssociatedAttributeManager+>>>>>>> daa98bf1f3 (Simplify Page <> Attribute relation)class AssignedPageAttributeValue(SortableModel):@@ -12,26 +16,22 @@ class AssignedPageAttributeValue(SortableModel):on_delete=models.CASCADE,related_name="pagevalueassignment",)- assignment = models.ForeignKey(- "AssignedPageAttribute",- on_delete=models.CASCADE,- related_name="pagevalueassignment",- )page = models.ForeignKey(Page,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", "page"),)ordering = ("sort_order", "pk")indexes = [BTreeIndex(fields=["page"], name="assignedpageattrvalue_page_idx")]def get_ordering_queryset(self):+<<<<<<< HEADreturn self.assignment.pagevalueassignment.all()@@ -51,6 +51,9 @@ class AssignedPageAttribute(BaseAssignedAttribute):class Meta:unique_together = (("page", "assignment"),)+=======+ return self.page.attributevalues.all()+>>>>>>> daa98bf1f3 (Simplify Page <> Attribute relation)class AttributePage(SortableModel):@@ -60,13 +63,6 @@ class AttributePage(SortableModel):page_type = models.ForeignKey(PageType, related_name="attributepage", on_delete=models.CASCADE)- assigned_pages = models.ManyToManyField(- Page,- blank=True,- through=AssignedPageAttribute,- through_fields=("assignment", "page"),- related_name="attributesrelated",- )objects = AssociatedAttributeManager()diff --git a/saleor/attribute/tests/model_helpers.py b/saleor/attribute/tests/model_helpers.pynew file mode 100644index 0000000000..cde5d51cec--- /dev/null+++ b/saleor/attribute/tests/model_helpers.py@@ -0,0 +1,26 @@+from django.db.models.expressions import Exists, OuterRef++from ...page.models import Page+from ..models import (+ AssignedPageAttributeValue,+ Attribute,+ AttributePage,+ AttributeValue,+)+++def get_page_attributes(page: Page):+ page_attributes = AttributePage.objects.filter(page_type_id=page.page_type_id)++ return Attribute.objects.filter(+ Exists(page_attributes.filter(attribute_id=OuterRef("id")))+ ).order_by("attributepage__sort_order")+++def get_page_attribute_values(page: Page, attribute: Attribute):+ assigned_values = AssignedPageAttributeValue.objects.filter(page_id=page.pk)++ values = AttributeValue.objects.filter(attribute_id=attribute.pk)+ return values.filter(+ Exists(assigned_values.filter(value_id=OuterRef("id"))),+ ).order_by("pagevalueassignment__sort_order")diff --git a/saleor/attribute/tests/test_utils.py b/saleor/attribute/tests/test_utils.pyindex f1d1b2dcd6..27dac2983a 100644--- a/saleor/attribute/tests/test_utils.py+++ b/saleor/attribute/tests/test_utils.py@@ -1,7 +1,9 @@import pytest+from ...attribute.models import AssignedPageAttributeValuefrom ...product.models import ProductTypefrom ..utils import associate_attribute_values_to_instance+from .model_helpers import get_page_attribute_values, get_page_attributesdef test_associate_attribute_to_non_product_instance(color_attribute):@@ -74,24 +76,28 @@ def test_associate_attribute_to_product_instance_multiple_values(def test_associate_attribute_to_page_instance_multiple_values(page):"""Ensure multiple values in proper order are assigned."""- old_assignment = page.attributes.first()- assert old_assignment is not None, "The page doesn't have attribute-values"- assert old_assignment.values.count() == 1+ attribute = get_page_attributes(page).first()+ assert attribute is not None, "The page doesn't have attribute-values"+ assert get_page_attribute_values(page, attribute).count() == 1- attribute = old_assignment.attributevalues = attribute.values.all()# Clear the values- new_assignment = associate_attribute_values_to_instance(- page, attribute, values[1], values[0]- )+ associate_attribute_values_to_instance(page, 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.pagevalueassignment.values_list("value_id", "sort_order")- ) == [(values[1].pk, 0), (values[0].pk, 1)]+ assigned_values = (+ AssignedPageAttributeValue.objects.filter(+ page_id=page.pk, value__attribute_id=attribute.id+ )+ .prefetch_related("value")+ .order_by("sort_order")+ )+ assert len(assigned_values) == 2+ assert assigned_values[0].value == values[1]+ assert assigned_values[0].sort_order == 0+ assert assigned_values[1].value == values[0]+ assert assigned_values[1].sort_order == 1def test_associate_attribute_to_variant_instance_multiple_values(diff --git a/saleor/attribute/utils.py b/saleor/attribute/utils.pyindex 42951aa37a..d87578f4d9 100644--- a/saleor/attribute/utils.py+++ b/saleor/attribute/utils.py@@ -1,10 +1,11 @@from collections.abc import Iterablefrom typing import TYPE_CHECKING, Union+from django.db.models.expressions import Exists, OuterRef+from ..page.models import Pagefrom ..product.models import Product, ProductVariantfrom .models import (- AssignedPageAttribute,AssignedPageAttributeValue,AssignedProductAttribute,AssignedProductAttributeValue,@@ -14,21 +15,36 @@ from .models import (AttributeValue,)-AttributeAssignmentType = Union[- AssignedProductAttribute, AssignedVariantAttribute, AssignedPageAttribute-]+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,-) -> AttributeAssignmentType:+) -> Union[None, AttributeAssignmentType]:"""Assign given attribute values to a product or variant.Note: be aware this function invokes the ``set`` method on the instance's@@ -41,27 +57,7 @@ def associate_attribute_values_to_instance(validate_attribute_owns_values(attribute, values_ids)# Associate the attribute and the passed values- assignment = _associate_attribute_to_instance(instance, attribute.pk)- assignment.values.set(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- if isinstance(instance, Product):- AssignedProductAttributeValue.objects.filter(- assignment_id=assignment.pk- ).update(product_id=instance.pk)-- # This code will be deleted in new release (3.17), it is temporary solution between- # releases to keep database in sync- elif isinstance(instance, Page):- AssignedPageAttributeValue.objects.filter(assignment_id=assignment.pk).update(- page_id=instance.pk- )-- sort_assigned_attribute_values(instance, assignment, values)-- return assignment+ return _associate_attribute_to_instance(instance, attribute, *values)def validate_attribute_owns_values(attribute: Attribute, value_ids: set[int]) -> None:@@ -79,48 +75,85 @@ def validate_attribute_owns_values(attribute: Attribute, value_ids: set[int]) ->def _associate_attribute_to_instance(- instance: T_INSTANCE, attribute_pk: int-) -> AttributeAssignmentType:- """Associate a given attribute to an instance."""+ instance: T_INSTANCE,+ attribute: Attribute,+ *values: AttributeValue,+) -> Union[None, AttributeAssignmentType]:+ """Associate a given attribute to an instance.++ For a given instance assign an attribute to it and set values based on *values.++ Note: this will clean any value that already exist there.++ This function is under rebuilding while we move away from intermediate models+ for attribute relations++ See:+ https://github.com/saleor/saleor/issues/12881+ """+ if isinstance(instance, Page):+ # Clear all assignments that don't match the values we'd like to assign+ 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()++ # Create new assignments+ for value in values:+ AssignedPageAttributeValue.objects.get_or_create(page=instance, value=value)++ 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)+ ] = instance.product_type.attributeproduct.get(attribute_id=attribute.pk)assignment, _ = AssignedProductAttribute.objects.get_or_create(product=instance, assignment=attribute_rel)- elif isinstance(instance, ProductVariant):- attribute_rel = instance.product.product_type.attributevariant.get(- attribute_id=attribute_pk+ assignment.values.set(values)++ sort_assigned_attribute_values_using_assignment(instance, assignment, 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+ AssignedProductAttributeValue.objects.filter(+ assignment_id=assignment.pk+ ).update(product_id=instance.pk)++ return assignment++ if isinstance(instance, ProductVariant):+ attribute_variant = instance.product.product_type.attributevariant.get(+ attribute_id=attribute.pk)assignment, _ = AssignedVariantAttribute.objects.get_or_create(- variant=instance, assignment=attribute_rel- )- elif isinstance(instance, Page):- attribute_rel = instance.page_type.attributepage.get(attribute_id=attribute_pk)- assignment, _ = AssignedPageAttribute.objects.get_or_create(- page=instance, assignment=attribute_rel+ variant=instance, assignment=attribute_variant)- else:- raise AssertionError(f"{instance.__class__.__name__} is unsupported")+ assignment.values.set(values)- return assignment+ sort_assigned_attribute_values_using_assignment(instance, assignment, values)+ return assignment+ raise AssertionError(f"{instance.__class__.__name__} is unsupported")-def sort_assigned_attribute_values(++def sort_assigned_attribute_values_using_assignment(instance: T_INSTANCE,assignment: AttributeAssignmentType,values: Iterable[AttributeValue],) -> None:"""Sort assigned attribute values based on values list order."""-instance_to_value_assignment_mapping = {- "Product": ("productvalueassignment", AssignedProductAttributeValue),"ProductVariant": ("variantvalueassignment", AssignedVariantAttributeValue),- "Page": ("pagevalueassignment", AssignedPageAttributeValue),+ "Product": ("productvalueassignment", AssignedProductAttributeValue),}assignment_lookup, assignment_model = instance_to_value_assignment_mapping[instance.__class__.__name__@@ -135,3 +168,23 @@ def sort_assigned_attribute_values(value_assignment.sort_order = indexassignment_model._default_manager.bulk_update(values_assignment, ["sort_order"])+++def sort_assigned_attribute_values(+ instance: Page,+ 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"))),+ )+ )+ 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++ AssignedPageAttributeValue.objects.bulk_update(values_assignment, ["sort_order"])diff --git a/saleor/core/utils/random_data.py b/saleor/core/utils/random_data.pyindex bdeab53e97..8a155b5225 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 (- AssignedPageAttribute,AssignedProductAttribute,AssignedProductAttributeValue,AssignedVariantAttribute,@@ -403,20 +402,6 @@ def assign_attribute_values_to_variants(variant_attribute_values):AssignedVariantAttributeValue.objects.update_or_create(pk=pk, defaults=defaults)-def assign_attributes_to_pages(page_attributes):- for value in page_attributes:- pk = value["pk"]- defaults = dict(value["fields"])- defaults["page_id"] = defaults.pop("page")- defaults["assignment_id"] = defaults.pop("assignment")- assigned_values = defaults.pop("values")- assoc, created = AssignedPageAttribute.objects.update_or_create(- pk=pk, defaults=defaults- )- if created:- assoc.values.set(AttributeValue.objects.filter(pk__in=assigned_values))--def set_field_as_money(defaults, field):amount_field = f"{field}_amount"if amount_field in defaults and defaults[amount_field] is not None:@@ -470,7 +455,6 @@ def create_products_by_schema(placeholder_dir, create_images):assign_attribute_values_to_variants(types["attribute.assignedvariantattributevalue"])- assign_attributes_to_pages(page_attributes=types["attribute.assignedpageattribute"])create_collections(data=types["product.collection"], placeholder_dir=placeholder_dir)diff --git a/saleor/graphql/attribute/utils.py b/saleor/graphql/attribute/utils.pyindex 4241a00f28..3fbfc532e3 100644--- a/saleor/graphql/attribute/utils.py+++ b/saleor/graphql/attribute/utils.py@@ -17,7 +17,10 @@ from text_unidecode import unidecodefrom ...attribute import AttributeEntityType, AttributeInputType, AttributeTypefrom ...attribute import models as attribute_models-from ...attribute.utils import associate_attribute_values_to_instance+from ...attribute.utils import (+ associate_attribute_values_to_instance,+ disassociate_attributes_from_instance,+)from ...core.utils import (generate_unique_slug,prepare_unique_attribute_value_slug,@@ -176,9 +179,10 @@ class AttributeAssignmentMixin:lookup_field: str,value,):- assignment = instance.attributes.filter(+ assignment = instance.attributes.filter( # type:ignore[union-attr]assignment__attribute=attribute, **{f"values__{lookup_field}": value}).first()+return (Noneif assignment is None@@ -423,7 +427,7 @@ class AttributeAssignmentMixin:# drop attribute assignment model when values are unassigned from instanceif clean_assignment:- instance.attributes.filter(+ instance.attributes.filter( # type:ignore[union-attr]assignment__attribute_id__in=clean_assignment).delete()@@ -756,6 +760,80 @@ class AttributeAssignmentMixin:return (value,)+class PageAttributeAssignmentMixin(AttributeAssignmentMixin):+ # TODO: merge the code here with the mixin above+ # when all attribute relations are cleaned up++ @classmethod+ def _get_assigned_attribute_value_if_exists(+ cls,+ instance: T_INSTANCE,+ attribute: attribute_models.Attribute,+ lookup_field: str,+ value,+ ):+ return (+ attribute.values.filter(+ pagevalueassignment__page_id=instance.pk,+ **{lookup_field: value},+ ).first()+ or None+ )++ @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,+ }+ clean_assignment = []++ 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+ )+ 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)++def get_variant_selection_attributes(qs: "QuerySet") -> "QuerySet":return qs.filter(type=AttributeType.PRODUCT_TYPE, attributevariant__variant_selection=Truediff --git a/saleor/graphql/page/bulk_mutations.py b/saleor/graphql/page/bulk_mutations.pyindex c609b0086b..7005a06b76 100644--- a/saleor/graphql/page/bulk_mutations.py+++ b/saleor/graphql/page/bulk_mutations.py@@ -1,5 +1,6 @@import graphenefrom django.core.exceptions import ValidationError+from django.db.models.expressions import Exists, OuterReffrom ...attribute import AttributeInputTypefrom ...attribute import models as attribute_models@@ -41,9 +42,16 @@ class PageBulkDelete(ModelBulkDeleteMutation):@staticmethoddef delete_assigned_attribute_values(instance_pks):+ assigned_values = attribute_models.AssignedPageAttributeValue.objects.filter(+ page_id__in=instance_pks+ )+ attributes = attribute_models.Attribute.objects.filter(+ input_type__in=AttributeInputType.TYPES_WITH_UNIQUE_VALUES+ )+attribute_models.AttributeValue.objects.filter(- pageassignments__page_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()@@ -109,7 +117,14 @@ class PageTypeBulkDelete(ModelBulkDeleteMutation):@staticmethoddef delete_assigned_attribute_values(instance_pks):+ assigned_values = attribute_models.AssignedPageAttributeValue.objects.filter(+ page__page_type_id__in=instance_pks+ )+ attributes = attribute_models.Attribute.objects.filter(+ input_type__in=AttributeInputType.TYPES_WITH_UNIQUE_VALUES+ )+attribute_models.AttributeValue.objects.filter(- pageassignments__assignment__page_type_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()diff --git a/saleor/graphql/page/dataloaders.py b/saleor/graphql/page/dataloaders.pyindex 58cc0c9b8d..4b0ae7c8d5 100644--- a/saleor/graphql/page/dataloaders.py+++ b/saleor/graphql/page/dataloaders.py@@ -1,15 +1,11 @@from collections import defaultdict-from promise import Promise+from django.db.models import prefetch_related_objects-from ...attribute.models import (- AssignedPageAttribute,- AssignedPageAttributeValue,- AttributePage,-)+from ...attribute.models import AssignedPageAttributeValue, AttributePagefrom ...page.models import Page, PageTypefrom ...permission.enums import PagePermissions-from ..attribute.dataloaders import AttributesByAttributeId, AttributeValueByIdLoader+from ..attribute.dataloaders import AttributesByAttributeIdfrom ..core.dataloaders import DataLoaderfrom ..utils import get_user_or_app_from_context@@ -90,156 +86,62 @@ class PageAttributesByPageTypeIdLoader(DataLoader):)-class AttributePagesByPageTypeIdLoader(DataLoader):- """Loads AttributePage objects by page type ID."""-- context_key = "attributepages_by_pagetype"-- def batch_load(self, keys):- requestor = get_user_or_app_from_context(self.context)- if (- requestor- and requestor.is_active- and requestor.has_perm(PagePermissions.MANAGE_PAGES)- ):- qs = AttributePage.objects.using(self.database_connection_name).all()- else:- qs = AttributePage.objects.using(self.database_connection_name).filter(- attribute__visible_in_storefront=True- )- attribute_pages = qs.filter(page_type_id__in=keys)- pagetype_to_attributepages = defaultdict(list)- for attribute_page in attribute_pages:- pagetype_to_attributepages[attribute_page.page_type_id].append(- attribute_page- )- return [pagetype_to_attributepages[key] for key in keys]---class AssignedPageAttributesByPageIdLoader(DataLoader):- context_key = "assignedpageattributes_by_page"+class AttributeValuesByPageIdLoader(DataLoader):+ context_key = "attributevalues_by_page"def batch_load(self, keys):- requestor = get_user_or_app_from_context(self.context)- if (- requestor- and requestor.is_active- and requestor.has_perm(PagePermissions.MANAGE_PAGES)- ):- qs = AssignedPageAttribute.objects.using(- self.database_connection_name- ).all()- else:- qs = AssignedPageAttribute.objects.using(- self.database_connection_name- ).filter(assignment__attribute__visible_in_storefront=True)- assigned_page_attributes = qs.filter(page_id__in=keys)- page_to_assignedattributes = defaultdict(list)- for assigned_page_attribute in assigned_page_attributes:- page_to_assignedattributes[assigned_page_attribute.page_id].append(- assigned_page_attribute+ # 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(+ AssignedPageAttributeValue.objects.using(self.database_connection_name)+ .filter(page_id__in=keys)+ .iterator()+ )+ prefetch_related_objects(attribute_values, "value")++ def with_pages(pages):+ pages = [page for page in pages if page]+ page_type_ids = [p.page_type_id for p in pages]++ def with_attributes(attribute_pages):+ page_type_attrubutes = dict(zip(page_type_ids, attribute_pages))+ assigned_page_map = defaultdict(list)++ for page in pages:+ page_values = [+ page_value.value+ for page_value in attribute_values+ if page_value.page_id == page.id+ ]++ attributes = page_type_attrubutes[page.page_type_id]+ for attribute_tuple in attributes:+ attribute = attribute_tuple+ values = [+ value+ for value in page_values+ if value.attribute_id == attribute.id+ ]+ assigned_page_map[page.id].append(+ {+ "attribute": attribute,+ "values": values,+ }+ )+ return [assigned_page_map[key] for key in keys]++ return (+ PageAttributesByPageTypeIdLoader(self.context)+ .load_many(page_type_ids)+ .then(with_attributes))- return [page_to_assignedattributes[page_id] for page_id in keys]---class AttributeValuesByAssignedPageAttributeIdLoader(DataLoader):- context_key = "attributevalues_by_assigned_pageattribute"-- def batch_load(self, keys):- attribute_values = AssignedPageAttributeValue.objects.using(- self.database_connection_name- ).filter(assignment_id__in=keys)- value_ids = [a.value_id for a in attribute_values]-- def map_assignment_to_values(values):- value_map = dict(zip(value_ids, values))- assigned_page_map = defaultdict(list)- for attribute_value in attribute_values:- assigned_page_map[attribute_value.assignment_id].append(- value_map.get(attribute_value.value_id)- )- return [assigned_page_map[key] for key in keys]- return (- AttributeValueByIdLoader(self.context)- .load_many(value_ids)- .then(map_assignment_to_values)- )+ return PageByIdLoader(self.context).load_many(keys).then(with_pages)class SelectedAttributesByPageIdLoader(DataLoader):context_key = "selectedattributes_by_page"- def batch_load(self, keys):- def with_pages_and_assigned_attributes(result):- pages, page_attributes = result- assigned_page_attributes_ids = list(- {attr.id for attrs in page_attributes for attr in attrs}- )- page_type_ids = [page.page_type_id for page in pages]- page_attributes = dict(zip(keys, page_attributes))-- def with_attribute_pages_and_values(result):- attribute_pages, attribute_values = result- attribute_ids = list(- {ap.attribute_id for aps in attribute_pages for ap in aps}- )- attribute_pages = dict(zip(page_type_ids, attribute_pages))- attribute_values = dict(- zip(assigned_page_attributes_ids, attribute_values)- )-- def with_attributes(attributes):- id_to_attribute = dict(zip(attribute_ids, attributes))- selected_attributes_map = defaultdict(list)- for key, page in zip(keys, pages):- assigned_pagetype_attributes = attribute_pages[- page.page_type_id- ]- assigned_page_attributes = page_attributes[key]- for assigned_pagetype_attribute in assigned_pagetype_attributes:- page_assignment = next(- (- apa- for apa in assigned_page_attributes- if apa.assignment_id- == assigned_pagetype_attribute.id- ),- None,- )- attribute = id_to_attribute[- assigned_pagetype_attribute.attribute_id- ]- if page_assignment:- values = attribute_values[page_assignment.id]- else:- values = []- selected_attributes_map[key].append(- {"values": values, "attribute": attribute}- )- return [selected_attributes_map[key] for key in keys]-- return (- AttributesByAttributeId(self.context)- .load_many(attribute_ids)- .then(with_attributes)- )-- attribute_pages = AttributePagesByPageTypeIdLoader(self.context).load_many(- page_type_ids- )- attribute_values = AttributeValuesByAssignedPageAttributeIdLoader(- self.context- ).load_many(assigned_page_attributes_ids)- return Promise.all([attribute_pages, attribute_values]).then(- with_attribute_pages_and_values- )-- pages = PageByIdLoader(self.context).load_many(keys)- assigned_attributes = AssignedPageAttributesByPageIdLoader(- self.context- ).load_many(keys)-- return Promise.all([pages, assigned_attributes]).then(- with_pages_and_assigned_attributes- )+ def batch_load(self, page_ids):+ return AttributeValuesByPageIdLoader(self.context).load_many(page_ids)diff --git a/saleor/graphql/page/mutations/page_create.py b/saleor/graphql/page/mutations/page_create.pyindex 452ea1dd6b..042e143358 100644--- a/saleor/graphql/page/mutations/page_create.py+++ b/saleor/graphql/page/mutations/page_create.py@@ -9,7 +9,7 @@ from ....page import modelsfrom ....page.error_codes import PageErrorCodefrom ....permission.enums import PagePermissionsfrom ...attribute.types import AttributeValueInput-from ...attribute.utils import AttributeAssignmentMixin+from ...attribute.utils import PageAttributeAssignmentMixinfrom ...core import ResolveInfofrom ...core.descriptions import ADDED_IN_33, DEPRECATED_IN_3X_INPUT, RICH_CONTENTfrom ...core.doc_category import DOC_CATEGORY_PAGES@@ -69,11 +69,11 @@ class PageCreate(ModelMutation):@classmethoddef clean_attributes(cls, attributes: dict, page_type: models.PageType):- attributes_qs = page_type.page_attributes.all()- attributes = AttributeAssignmentMixin.clean_input(+ attributes_qs = page_type.page_attributes.prefetch_related("values")+ cleaned_attributes = PageAttributeAssignmentMixin.clean_input(attributes, attributes_qs, is_page_attributes=True)- return attributes+ return cleaned_attributes@classmethoddef clean_input(cls, info: ResolveInfo, instance, data, **kwargs):@@ -129,7 +129,7 @@ class PageCreate(ModelMutation):attributes = cleaned_data.get("attributes")if attributes:- AttributeAssignmentMixin.save(instance, attributes)+ PageAttributeAssignmentMixin.save(instance, attributes)@classmethoddef save(cls, info: ResolveInfo, instance, cleaned_input):diff --git a/saleor/graphql/page/mutations/page_delete.py b/saleor/graphql/page/mutations/page_delete.pyindex c9cb1759c5..8397171a01 100644--- a/saleor/graphql/page/mutations/page_delete.py+++ b/saleor/graphql/page/mutations/page_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@@ -36,7 +37,14 @@ class PageDelete(ModelDeleteMutation):@staticmethoddef delete_assigned_attribute_values(instance):+ assigned_values = attribute_models.AssignedPageAttributeValue.objects.filter(+ page_id=instance.pk+ )+ attributes = attribute_models.Attribute.objects.filter(+ input_type__in=AttributeInputType.TYPES_WITH_UNIQUE_VALUES+ )+attribute_models.AttributeValue.objects.filter(- pageassignments__page_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/page/mutations/page_reorder_attribute_values.py b/saleor/graphql/page/mutations/page_reorder_attribute_values.pyindex 55aa73f241..3b6607a16a 100644--- a/saleor/graphql/page/mutations/page_reorder_attribute_values.py+++ b/saleor/graphql/page/mutations/page_reorder_attribute_values.py@@ -1,14 +1,17 @@import graphenefrom django.core.exceptions import ObjectDoesNotExist, ValidationError+from ....core.tracing import traced_atomic_transactionfrom ....page import models as page_modelsfrom ....page.error_codes import PageErrorCodefrom ....permission.enums import PagePermissionsfrom ...attribute.mutations import BaseReorderAttributeValuesMutation+from ...attribute.types import Attributefrom ...core import ResolveInfofrom ...core.doc_category import DOC_CATEGORY_PAGESfrom ...core.inputs import ReorderInputfrom ...core.types import NonNullList, PageError+from ...core.utils.reordering import perform_reorderingfrom ...page.types import Page@@ -40,15 +43,44 @@ class PageReorderAttributeValues(BaseReorderAttributeValuesMutation):@classmethoddef perform_mutation(cls, _root, _info: ResolveInfo, /, **data):page_id = data["page_id"]- page = cls.perform(page_id, "page", data, "pagevalueassignment", PageErrorCode)+ page = cls.perform(page_id, "page", data, "attributevalues", PageErrorCode)return PageReorderAttributeValues(page=page)+ @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 get_instance(cls, instance_id: str):pk = cls.get_global_id_or_error(instance_id, only_type=Page, field="page_id")try:- page = page_models.Page.objects.prefetch_related("attributes").get(pk=pk)+ page = page_models.Page.objects.get(pk=pk)except ObjectDoesNotExist:raise ValidationError({@@ -59,3 +91,28 @@ class PageReorderAttributeValues(BaseReorderAttributeValuesMutation):})return page++ @classmethod+ def validate_attribute_assignment(+ cls, instance, instance_type, attribute_id: str, error_code_enum+ ):+ """Validate if this attribute_id is assigned to this page."""+ attribute_pk = cls.get_global_id_or_error(+ attribute_id, only_type=Attribute, field="attribute_id"+ )++ attribute_assignment = instance.page_type.attributepage.filter(+ attribute_id=attribute_pk+ ).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_assignmentdiff --git a/saleor/graphql/page/mutations/page_type_delete.py b/saleor/graphql/page/mutations/page_type_delete.pyindex 8a364a454b..c26414bacb 100644--- a/saleor/graphql/page/mutations/page_type_delete.py+++ b/saleor/graphql/page/mutations/page_type_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@@ -35,9 +36,16 @@ class PageTypeDelete(ModelDeleteMutation):@staticmethoddef delete_assigned_attribute_values(instance_pk):+ assigned_values = attribute_models.AssignedPageAttributeValue.objects.filter(+ page__page_type_id=instance_pk+ )+ attributes = attribute_models.Attribute.objects.filter(+ input_type__in=AttributeInputType.TYPES_WITH_UNIQUE_VALUES+ )+attribute_models.AttributeValue.objects.filter(- attribute__input_type__in=AttributeInputType.TYPES_WITH_UNIQUE_VALUES,- pageassignments__assignment__page_type_id=instance_pk,+ Exists(assigned_values.filter(value_id=OuterRef("id"))),+ Exists(attributes.filter(id=OuterRef("attribute_id"))),).delete()@classmethoddiff --git a/saleor/graphql/page/mutations/page_update.py b/saleor/graphql/page/mutations/page_update.pyindex 2c188d7c6e..10626f997b 100644--- a/saleor/graphql/page/mutations/page_update.py+++ b/saleor/graphql/page/mutations/page_update.py@@ -2,7 +2,7 @@ import graphenefrom ....page import modelsfrom ....permission.enums import PagePermissions-from ...attribute.utils import AttributeAssignmentMixin+from ...attribute.utils import PageAttributeAssignmentMixinfrom ...core import ResolveInfofrom ...core.types import PageErrorfrom ...plugins.dataloaders import get_plugin_manager_promise@@ -27,11 +27,11 @@ class PageUpdate(PageCreate):@classmethoddef clean_attributes(cls, attributes: dict, page_type: models.PageType):- attributes_qs = page_type.page_attributes.all()- attributes = AttributeAssignmentMixin.clean_input(+ attributes_qs = page_type.page_attributes.prefetch_related("values")+ cleaned_attributes = PageAttributeAssignmentMixin.clean_input(attributes, attributes_qs, creation=False, is_page_attributes=True)- return attributes+ return cleaned_attributes@classmethoddef save(cls, info: ResolveInfo, instance, cleaned_input):diff --git a/saleor/graphql/page/tests/mutations/test_page_reorder_attribute_values.py b/saleor/graphql/page/tests/mutations/test_page_reorder_attribute_values.pyindex 014be89382..bc9ee500bb 100644--- a/saleor/graphql/page/tests/mutations/test_page_reorder_attribute_values.py+++ b/saleor/graphql/page/tests/mutations/test_page_reorder_attribute_values.py@@ -1,6 +1,6 @@import graphene-from .....attribute.models import AssignedPageAttributeValue, AttributeValue+from .....attribute.models import AttributeValuefrom .....attribute.utils import associate_attribute_values_to_instancefrom .....page.error_codes import PageErrorCodefrom ....tests.utils import get_graphql_content@@ -112,10 +112,10 @@ def test_sort_page_attribute_values(assert db_type == "AttributeValue"assert int(value_pk) == expected_pk- apa_values = AssignedPageAttributeValue.objects.filter(assignment__page_id=page.id)+ apa_values = page.attributevalues.filter(+ value__attribute_id=page_type_page_reference_attribute.id+ )assert len(apa_values) == 3- for assigned_page in apa_values:- assert assigned_page.assignment.page.id == assigned_page.page.iddef test_sort_page_attribute_values_invalid_attribute_id(@@ -176,7 +176,7 @@ def test_sort_page_attribute_values_invalid_value_id(permission_manage_pages,page,page_type_page_reference_attribute,- size_page_attribute,+ color_attribute,):staff_api_client.user.user_permissions.add(permission_manage_pages)@@ -212,7 +212,7 @@ def test_sort_page_attribute_values_invalid_value_id()invalid_value_id = graphene.Node.to_global_id(- "AttributeValue", size_page_attribute.values.first().pk+ "AttributeValue", color_attribute.values.first().pk)variables = {diff --git a/saleor/graphql/page/tests/mutations/test_page_update.py b/saleor/graphql/page/tests/mutations/test_page_update.pyindex 9d9abeafda..ed5851511c 100644--- a/saleor/graphql/page/tests/mutations/test_page_update.py+++ b/saleor/graphql/page/tests/mutations/test_page_update.py@@ -13,6 +13,10 @@ from django.utils.text import slugifyfrom freezegun import freeze_timefrom .....attribute.models import AttributeValue+from .....attribute.tests.model_helpers import (+ get_page_attribute_values,+ get_page_attributes,+)from .....attribute.utils import associate_attribute_values_to_instancefrom .....page.error_codes import PageErrorCodefrom .....page.models import Page@@ -97,7 +101,6 @@ def test_update_page(staff_api_client, permission_manage_pages, page):assert data["page"]["slug"] == new_slugexpected_attributes = []- page_attr = page.attributes.all()for attr in page_type.page_attributes.all():if attr.slug != tag_attr.slug:values = [@@ -108,9 +111,9 @@ def test_update_page(staff_api_client, permission_manage_pages, page):"reference": None,"plainText": None,}- for slug, name in page_attr.filter(- assignment__attribute=attr- ).values_list("values__slug", "values__name")+ for slug, name in get_page_attribute_values(page, attr).values_list(+ "slug", "name"+ )]else:values = [@@ -225,7 +228,6 @@ def test_update_page_only_title(staff_api_client, permission_manage_pages, page)assert data["page"]["slug"] == new_slugexpected_attributes = []- page_attr = page.attributes.all()for attr in page_type.page_attributes.all():values = [{@@ -235,8 +237,8 @@ def test_update_page_only_title(staff_api_client, permission_manage_pages, page)"reference": None,"plainText": None,}- for slug, name in page_attr.filter(assignment__attribute=attr).values_list(- "values__slug", "values__name"+ for slug, name in get_page_attribute_values(page, attr).values_list(+ "slug", "name")]attr_data = {@@ -357,8 +359,10 @@ def test_update_page_clear_values(staff_api_client, permission_manage_pages, pag# givenquery = UPDATE_PAGE_MUTATION- page_attr = page.attributes.first()- attribute = page_attr.assignment.attribute+ page_attr = get_page_attributes(page).first()+ assert page_attr is not None++ attribute = page_attrattribute.value_required = Falseattribute.save(update_fields=["value_required"])@@ -384,8 +388,7 @@ def test_update_page_clear_values(staff_api_client, permission_manage_pages, pagassert data["page"]assert not data["page"]["attributes"][0]["values"]- with pytest.raises(page_attr._meta.model.DoesNotExist):- page_attr.refresh_from_db()+ assert not get_page_attribute_values(page, page_attr).exists()def test_update_page_with_page_reference_attribute_new_value(@@ -1092,8 +1095,10 @@ def test_update_page_change_attribute_values_ordering(attr_value_1,)+ attribute = get_page_attributes(page).first()+ assert attribute is not Noneassert list(- page.attributes.first().pagevalueassignment.values_list("value_id", flat=True)+ get_page_attribute_values(page, attribute).values_list("id", flat=True)) == [attr_value_3.pk, attr_value_2.pk, attr_value_1.pk]new_ref_order = [product_list[1], product_list[0], product_list[2]]@@ -1133,9 +1138,10 @@ def test_update_page_change_attribute_values_ordering(graphene.Node.to_global_id("AttributeValue", val.pk)for val in [attr_value_2, attr_value_1, attr_value_3]]- page.refresh_from_db()++ # page.refresh_from_db()assert list(- page.attributes.first().pagevalueassignment.values_list("value_id", flat=True)+ get_page_attribute_values(page, attribute).values_list("id", flat=True)) == [attr_value_2.pk, attr_value_1.pk, attr_value_3.pk]diff --git a/saleor/graphql/page/tests/queries/test_page.py b/saleor/graphql/page/tests/queries/test_page.pyindex e2c0a3e836..265d829f10 100644--- a/saleor/graphql/page/tests/queries/test_page.py+++ b/saleor/graphql/page/tests/queries/test_page.py@@ -1,6 +1,10 @@import graphenefrom .....attribute.models import AttributeValue+from .....attribute.tests.model_helpers import (+ get_page_attribute_values,+ get_page_attributes,+)from .....attribute.utils import associate_attribute_values_to_instancefrom .....tests.utils import dummy_editorjsfrom ....tests.utils import get_graphql_content, get_graphql_content_from_response@@ -36,12 +40,11 @@ def test_query_published_page(user_api_client, page):page_type = page.page_type- assert page.attributes.count() == 1- page_attr_assigned = page.attributes.first()- page_attr = page_attr_assigned.attribute+ page_attr = get_page_attributes(page).first()+ assert page_attr is not None+ assert get_page_attribute_values(page, page_attr).count() == 1- assert page_attr_assigned.values.count() == 1- page_attr_value = page_attr_assigned.values.first()+ page_attr_value = page_attr.values.first()# query by IDvariables = {"id": graphene.Node.to_global_id("Page", page.id)}diff --git a/saleor/graphql/product/tests/queries/test_variant_query.py b/saleor/graphql/product/tests/queries/test_variant_query.pyindex af87ee0be7..b7021ed2d4 100644--- a/saleor/graphql/product/tests/queries/test_variant_query.py+++ b/saleor/graphql/product/tests/queries/test_variant_query.py@@ -534,9 +534,9 @@ def test_get_variant_by_id_with_variant_selection_filter()_associate_attribute_to_instance(- variant, file_attribute_with_file_input_type_without_values.pk+ variant, file_attribute_with_file_input_type_without_values)- _associate_attribute_to_instance(variant, size_attribute.pk)+ _associate_attribute_to_instance(variant, size_attribute)# whenresponse = staff_api_client.post_graphql(