Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Remove attribute.values (#18022)
Iga Karbowiak9cb9b2aee96e
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 9f942f89a6..3d0b57cf70 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -83,7 +83,6 @@ All notable, unreleased changes to this project will be documented in this file.- You can now filter and search attribute choices using the new `where` and `search` fields on the `attribute.choices` query.- Filtering products by `category` now also includes subcategories. The filter will return products that belong to the specified categories as well as their subcategories.- Deprecated `Transaction.gatewayResponse` field. Please migrate to Transaction API and Apps.-- Extend the `Attribute` type with a `values` field, allowing you to retrieve all values assigned to a specific attribute.- Add new `single-reference` attribute. You can now create a reference attribute that points to only one object (unlike the existing `reference` type, which supports multiple references).Like `reference`, the `single-reference` type can target entities defined in the `AttributeEntityTypeEnum`.- Extended support for filtering `products` by associated attributesdiff --git a/saleor/graphql/attribute/dataloaders.py b/saleor/graphql/attribute/dataloaders.pyindex e2fca8256e..ebef161583 100644--- a/saleor/graphql/attribute/dataloaders.py+++ b/saleor/graphql/attribute/dataloaders.py@@ -1,10 +1,7 @@from collections import defaultdict-from django.db.models import F, Window-from django.db.models.functions import RowNumber-from ...attribute.models import Attribute, AttributeValue-from ..core.dataloaders import DataLoader, DataLoaderWithLimit+from ..core.dataloaders import DataLoaderclass AttributeValuesByAttributeIdLoader(DataLoader[int, list[AttributeValue]]):@@ -22,33 +19,6 @@ class AttributeValuesByAttributeIdLoader(DataLoader[int, list[AttributeValue]]):return [attribute_to_attributevalues[attribute_id] for attribute_id in keys]-class AttributeValuesByAttributeIdWithLimitLoader(- DataLoaderWithLimit[int, list[AttributeValue]]-):- context_key = "attributevalues_by_attribute"-- def batch_load(self, keys):- attribute_values = (- AttributeValue.objects.using(self.database_connection_name)- .filter(attribute_id__in=keys)- .annotate(- row_num=Window(- expression=RowNumber(),- partition_by=F("attribute_id"),- order_by=F("id").asc(),- )- )- .filter(row_num__lte=self.limit)- )-- attribute_to_attributevalues = defaultdict(list)- for attribute_value in attribute_values.iterator(chunk_size=1000):- attribute_to_attributevalues[attribute_value.attribute_id].append(- attribute_value- )- return [attribute_to_attributevalues[attribute_id] for attribute_id in keys]--class AttributesByAttributeId(DataLoader[int, Attribute]):context_key = "attributes_by_id"diff --git a/saleor/graphql/attribute/tests/queries/test_attribute_query.py b/saleor/graphql/attribute/tests/queries/test_attribute_query.pyindex 67bc7f7152..a4ae695c10 100644--- a/saleor/graphql/attribute/tests/queries/test_attribute_query.py+++ b/saleor/graphql/attribute/tests/queries/test_attribute_query.py@@ -1,10 +1,10 @@import grapheneimport pytest-from django.db.models import Count, Q+from django.db.models import Qfrom graphene.utils.str_converters import to_camel_casefrom .....attribute import AttributeInputType, AttributeType-from .....attribute.models import Attribute, AttributeValue+from .....attribute.models import Attributefrom .....product import ProductTypeKindfrom .....product.models import Category, Collection, Product, ProductTypefrom .....tests.utils import dummy_editorjs@@ -783,107 +783,3 @@ def test_get_attribute_by_external_reference(data = content["data"]["attribute"]assert data["externalReference"] == ext_refassert data["id"] == graphene.Node.to_global_id("Attribute", attribute.id)---ATTRIBUTE_VALUES_QUERY = """-query ($limit: Int) {- attributes(first: 10) {- edges {- node {- id- name- slug- values(limit: $limit) {- name- slug- }- }- }- }-}-"""---def test_attributes_values_with_limit(- api_client, numeric_attribute, size_attribute, weight_attribute-):- # given- assert weight_attribute.values.count() > 1- assert size_attribute.values.count() > 1-- AttributeValue.objects.bulk_create(- [- AttributeValue(- slug="10", name="10", numeric=10, attribute=numeric_attribute- ),- AttributeValue(- slug="20", name="20", numeric=20, attribute=numeric_attribute- ),- AttributeValue(- slug="30", name="30", numeric=30, attribute=numeric_attribute- ),- ]- )- limit = 1- variables = {"limit": limit}-- # when- response = api_client.post_graphql(ATTRIBUTE_VALUES_QUERY, variables)-- # then- data = get_graphql_content(response)- attributes = data["data"]["attributes"]["edges"]- for attribute in attributes:- assert len(attribute["node"]["values"]) == limit---def test_attributes_values_default_limit(- api_client, numeric_attribute, size_attribute, weight_attribute-):- # given- AttributeValue.objects.bulk_create(- [- AttributeValue(- slug="10", name="10", numeric=10, attribute=numeric_attribute- ),- AttributeValue(- slug="20", name="20", numeric=20, attribute=numeric_attribute- ),- AttributeValue(- slug="30", name="30", numeric=30, attribute=numeric_attribute- ),- ]- )- attribute_count = {- att.slug: att.values_count- for att in Attribute.objects.annotate(values_count=Count("values"))- }-- # when- response = api_client.post_graphql(ATTRIBUTE_VALUES_QUERY, {})-- # then- data = get_graphql_content(response)- attributes = data["data"]["attributes"]["edges"]- for attribute in attributes:- assert (- len(attribute["node"]["values"])- == attribute_count[attribute["node"]["slug"]]- )---def test_attributes_values_limit_exceeded(api_client, weight_attribute):- # given- limit = 150- variables = {"limit": limit}-- # when- response = api_client.post_graphql(ATTRIBUTE_VALUES_QUERY, variables)-- # then- content = get_graphql_content_from_response(response)-- assert len(content["errors"]) == 1- assert content["errors"][0]["message"] == (- "The limit for attribute values cannot be greater than 100."- )diff --git a/saleor/graphql/attribute/types.py b/saleor/graphql/attribute/types.pyindex 5ea16764cd..5e73dc7440 100644--- a/saleor/graphql/attribute/types.py+++ b/saleor/graphql/attribute/types.py@@ -1,5 +1,4 @@import graphene-from django.conf import settingsfrom ...attribute import AttributeInputType, modelsfrom ...permission.enums import (@@ -44,7 +43,6 @@ from ..translations.fields import TranslationFieldfrom ..translations.types import AttributeTranslation, AttributeValueTranslationfrom .dataloaders import (AttributesByAttributeId,- AttributeValuesByAttributeIdWithLimitLoader,)from .descriptions import AttributeDescriptions, AttributeValueDescriptionsfrom .enums import AttributeEntityTypeEnum, AttributeInputTypeEnum, AttributeTypeEnum@@ -216,21 +214,6 @@ class Attribute(ChannelContextType[models.Attribute]):"Available only for attributes with predefined choices."),)- values = NonNullList(- AttributeValue,- description=(- "List of all existing attribute values. This includes all values"- " that have been assigned to attributes." + ADDED_IN_322- ),- limit=graphene.Int(- description=(- "Maximum number of attribute values to return. "- "The default value is also the maximum number of values "- "that can be fetched."- ),- default_value=settings.NESTED_QUERY_LIMIT,- ),- )value_required = graphene.Boolean(description=(@@ -353,24 +336,6 @@ class Attribute(ChannelContextType[models.Attribute]):channel_context_qs, info, kwargs, AttributeValueCountableConnection)- @staticmethod- def resolve_values(- root: ChannelContext[models.Attribute], info: ResolveInfo, limit: int, **kwargs- ):- attr = root.node-- def map_channel_context(values):- return [- ChannelContext(node=value, channel_slug=root.channel_slug)- for value in values- ]-- return (- AttributeValuesByAttributeIdWithLimitLoader(info.context, limit=limit)- .load(attr.id)- .then(map_channel_context)- )-@staticmethod@check_attribute_required_permissions()def resolve_value_required(diff --git a/saleor/graphql/core/dataloaders.py b/saleor/graphql/core/dataloaders.pyindex 9c54f7a29b..7aafe8c68e 100644--- a/saleor/graphql/core/dataloaders.py+++ b/saleor/graphql/core/dataloaders.py@@ -2,8 +2,6 @@ from collections import defaultdictfrom collections.abc import Iterablefrom typing import TypeVar-from django.conf import settings-from graphql import GraphQLErrorfrom promise import Promisefrom promise.dataloader import DataLoader as BaseLoader@@ -78,31 +76,6 @@ class DataLoader[K, R](BaseLoader):raise NotImplementedError()-class DataLoaderWithLimit(DataLoader[K, R]):- """Data loader base class that support a limit on the number of items returned."""-- def __new__(cls, context: SaleorContext, limit: int = settings.NESTED_QUERY_LIMIT):- loader = super().__new__(cls, context)- cls.limit_validation(limit)- loader.limit = limit- return loader-- def __init__(- self, context: SaleorContext, limit: int = settings.NESTED_QUERY_LIMIT- ) -> None:- if getattr(self, "limit", None) != limit:- self.limit_validation(limit)- self.limit = limit- super().__init__(context=context)-- @staticmethod- def limit_validation(limit: int) -> None:- if limit > settings.NESTED_QUERY_LIMIT:- raise GraphQLError(- f"The limit for attribute values cannot be greater than {settings.NESTED_QUERY_LIMIT}."- )--class BaseThumbnailBySizeAndFormatLoader(DataLoader[tuple[int, int, str | None], Thumbnail]):diff --git a/saleor/graphql/query_cost_map.py b/saleor/graphql/query_cost_map.pyindex d70e5eb4fd..e77510dc3a 100644--- a/saleor/graphql/query_cost_map.py+++ b/saleor/graphql/query_cost_map.py@@ -143,12 +143,6 @@ COST_MAP = {},"Attribute": {"choices": {"complexity": 1, "multipliers": ["first", "last"]},- "values": {- "complexity": 1,- "multipliers": [- "limit",- ],- },"productTypes": {"complexity": 1, "multipliers": ["first", "last"]},"productVariantTypes": {"complexity": 1, "multipliers": ["first", "last"]},},diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex 2382897e63..594a9c43c4 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -6123,18 +6123,6 @@ type Attribute implements Node & ObjectWithMetadata @doc(category: "Attributes")last: Int): AttributeValueCountableConnection- """- List of all existing attribute values. This includes all values that have been assigned to attributes.-- Added in Saleor 3.22.- """- values(- """- Maximum number of attribute values to return. The default value is also the maximum number of values that can be fetched.- """- limit: Int = 100- ): [AttributeValue!]-"""Whether the attribute requires values to be passed or not. Requires one of the following permissions: MANAGE_PAGES, MANAGE_PAGE_TYPES_AND_ATTRIBUTES, MANAGE_PRODUCTS, MANAGE_PRODUCT_TYPES_AND_ATTRIBUTES."""