Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Extend `Attribute` with `values` (#17924)
Iga Karbowiak7b1e8cee95d5
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex e94c149782..2a0b5e16fd 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -83,7 +83,7 @@ All notable, unreleased changes to this project will be documented in this file.- Attribute values now expose the `referencedObject`, allowing for easier access to the linked entity.- You can now filter and search attribute choices using the new `where` and `search` fields on the `attribute.choices` query.- 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.### Webhooks- Transaction webhooks responsible for processing payments can now return payment method details`, which will be associated with the corresponding transaction. See [docs](https://docs.saleor.io/developer/extending/webhooks/synchronous-events/transaction#response-4) to learn more.diff --git a/saleor/graphql/attribute/dataloaders.py b/saleor/graphql/attribute/dataloaders.pyindex ebef161583..e2fca8256e 100644--- a/saleor/graphql/attribute/dataloaders.py+++ b/saleor/graphql/attribute/dataloaders.py@@ -1,7 +1,10 @@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+from ..core.dataloaders import DataLoader, DataLoaderWithLimitclass AttributeValuesByAttributeIdLoader(DataLoader[int, list[AttributeValue]]):@@ -19,6 +22,33 @@ 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 a4ae695c10..cf11f723e3 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 Q+from django.db.models import Count, Qfrom graphene.utils.str_converters import to_camel_casefrom .....attribute import AttributeInputType, AttributeType-from .....attribute.models import Attribute+from .....attribute.models import Attribute, AttributeValuefrom .....product import ProductTypeKindfrom .....product.models import Category, Collection, Product, ProductTypefrom .....tests.utils import dummy_editorjs@@ -783,3 +783,95 @@ 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="num-10", attribute=numeric_attribute),+ AttributeValue(slug="20", name="num-20", attribute=numeric_attribute),+ AttributeValue(slug="30", name="num-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="num-10", attribute=numeric_attribute),+ AttributeValue(slug="20", name="num-20", attribute=numeric_attribute),+ AttributeValue(slug="30", name="num-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/tests/queries/test_attribute_where.py b/saleor/graphql/attribute/tests/queries/test_attribute_where.pyindex 9859b901a4..02b68e5eca 100644--- a/saleor/graphql/attribute/tests/queries/test_attribute_where.py+++ b/saleor/graphql/attribute/tests/queries/test_attribute_where.py@@ -1834,7 +1834,7 @@ def test_search_attributes_on_root_level(assert returned_attrs == {attributes[index].slug for index in indexes}-ATTRIBUTE_VALUES_FILTER_QUERY = """+ATTRIBUTE_CHOICES_FILTER_QUERY = """query($id: ID!, $where: AttributeValueWhereInput, $search: String) {attribute(id: $id) {name@@ -1854,14 +1854,14 @@ query($id: ID!, $where: AttributeValueWhereInput, $search: String) {def test_attributes_filter_by_choices_ids(api_client, color_attribute):# given- choices = AttributeValue.objects.bulk_create(+ values = AttributeValue.objects.bulk_create([AttributeValue(slug="choice-1", name="Choice 1", attribute=color_attribute),AttributeValue(slug="choice-2", name="Choice 2", attribute=color_attribute),AttributeValue(slug="choice-3", name="Choice 3", attribute=color_attribute),])- lookup_values = [choices[0], choices[2]]+ lookup_values = [values[0], values[2]]value_ids = [graphene.Node.to_global_id("AttributeValue", value.pk)for value in lookup_values@@ -1873,7 +1873,7 @@ def test_attributes_filter_by_choices_ids(api_client, color_attribute):}# when- response = api_client.post_graphql(ATTRIBUTE_VALUES_FILTER_QUERY, variables)+ response = api_client.post_graphql(ATTRIBUTE_CHOICES_FILTER_QUERY, variables)# thendata = get_graphql_content(response)@@ -1911,7 +1911,7 @@ def test_attributes_filter_by_choices_slug(where, indexes, api_client, color_att}# when- response = api_client.post_graphql(ATTRIBUTE_VALUES_FILTER_QUERY, variables)+ response = api_client.post_graphql(ATTRIBUTE_CHOICES_FILTER_QUERY, variables)# thendata = get_graphql_content(response)@@ -1949,7 +1949,7 @@ def test_attributes_filter_by_choices_name(where, indexes, api_client, color_att}# when- response = api_client.post_graphql(ATTRIBUTE_VALUES_FILTER_QUERY, variables)+ response = api_client.post_graphql(ATTRIBUTE_CHOICES_FILTER_QUERY, variables)# thendata = get_graphql_content(response)@@ -1988,7 +1988,7 @@ def test_attributes_filter_by_choices_search(}# when- response = api_client.post_graphql(ATTRIBUTE_VALUES_FILTER_QUERY, variables)+ response = api_client.post_graphql(ATTRIBUTE_CHOICES_FILTER_QUERY, variables)# thendata = get_graphql_content(response)diff --git a/saleor/graphql/attribute/types.py b/saleor/graphql/attribute/types.pyindex a8178cdf66..91c8165f80 100644--- a/saleor/graphql/attribute/types.py+++ b/saleor/graphql/attribute/types.py@@ -1,4 +1,5 @@import graphene+from django.conf import settingsfrom ...attribute import AttributeEntityType, AttributeInputType, modelsfrom ...permission.enums import (@@ -43,7 +44,10 @@ from ..page.dataloaders import PageByIdLoaderfrom ..product.dataloaders.products import ProductByIdLoader, ProductVariantByIdLoaderfrom ..translations.fields import TranslationFieldfrom ..translations.types import AttributeTranslation, AttributeValueTranslation-from .dataloaders import AttributesByAttributeId+from .dataloaders import (+ AttributesByAttributeId,+ AttributeValuesByAttributeIdWithLimitLoader,+)from .descriptions import AttributeDescriptions, AttributeValueDescriptionsfrom .enums import AttributeEntityTypeEnum, AttributeInputTypeEnum, AttributeTypeEnumfrom .filters import (@@ -247,14 +251,32 @@ class Attribute(ChannelContextType[models.Attribute]):filter=AttributeValueFilterInput(description=(f"Filtering options for attribute choices. {DEPRECATED_IN_3X_INPUT} "- "Use where filter instead."+ "Use `where` filter instead."),),where=AttributeValueWhereInput(description="Where filtering options for attribute choices." + ADDED_IN_322),search=graphene.String(description="Search attribute choices." + ADDED_IN_322),- description=AttributeDescriptions.VALUES,+ description=(+ "A list of predefined attribute choices available for selection. "+ "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(@@ -378,6 +400,24 @@ 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 7aafe8c68e..9c54f7a29b 100644--- a/saleor/graphql/core/dataloaders.py+++ b/saleor/graphql/core/dataloaders.py@@ -2,6 +2,8 @@ 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@@ -76,6 +78,31 @@ 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 bc28ba52fb..83ed65ddcb 100644--- a/saleor/graphql/query_cost_map.py+++ b/saleor/graphql/query_cost_map.py@@ -143,6 +143,7 @@ COST_MAP = {},"Attribute": {"choices": {"complexity": 1, "multipliers": ["first", "last"]},+ "values": {"complexity": 1, "multipliers": ["first", "last"]},"productTypes": {"complexity": 1, "multipliers": ["first", "last"]},"productVariantTypes": {"complexity": 1, "multipliers": ["first", "last"]},},@@ -301,7 +302,7 @@ COST_MAP = {},"SelectedAttribute": {"attribute": {"complexity": 1},- "values": {"complexity": 1, "multipliers": ["first", "last"]},+ "values": {"complexity": 1, "multipliers": ["limit"]},},"ShippingMethodChannelListing": {"channel": {"complexity": 1},diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex c96126098f..e8ee7bc6e7 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -6053,13 +6053,15 @@ type Attribute implements Node & ObjectWithMetadata @doc(category: "Attributes")"""The unit of attribute values."""unit: MeasurementUnitsEnum- """List of attribute's values."""+ """+ A list of predefined attribute choices available for selection. Available only for attributes with predefined choices.+ """choices("""Sort attribute choices."""sortBy: AttributeChoicesSortingInput"""Filtering options for attribute choices."""- filter: AttributeValueFilterInput @deprecated(reason: "Use where filter instead.")+ filter: AttributeValueFilterInput @deprecated(reason: "Use `where` filter instead.")"""Where filtering options for attribute choices.@@ -6092,6 +6094,18 @@ 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."""diff --git a/saleor/settings.py b/saleor/settings.pyindex 964ca6551e..f85ad62deb 100644--- a/saleor/settings.py+++ b/saleor/settings.py@@ -926,6 +926,8 @@ TRANSACTION_BATCH_FOR_RELEASING_FUNDS = os.environ.get("TRANSACTION_BATCH_FOR_RELEASING_FUNDS", 60)+NESTED_QUERY_LIMIT = int(os.environ.get("NESTED_QUERY_LIMIT", 100))+# The maximum SearchVector expression count allowed per index SQL statement# If the count is exceeded, the expression list will be truncated