Skip to content

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

Add AttributeWhere filter (#17923)

Iga Karbowiak421f362a87a4
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 7ee792c523..adad68f242 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -81,7 +81,7 @@ All notable, unreleased changes to this project will be documented in this file.
- `pageType.availableAttributes`
- Extend `AttributeEntityType` with `CATEGORY` and `COLLECTION`. You can now assign category and collection as a attribute reference.
- 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.
### 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/filters.py b/saleor/graphql/attribute/filters.py
index 0e0fc8288e..4fef743893 100644
--- a/saleor/graphql/attribute/filters.py
+++ b/saleor/graphql/attribute/filters.py
@@ -24,6 +24,7 @@ from ..core.filters import (
MetadataFilterBase,
MetadataWhereFilterBase,
OperationObjectTypeWhereFilter,
+ WhereFilterSet,
)
from ..core.filters.where_input import (
FilterInputDescriptions,
@@ -92,6 +93,11 @@ def filter_by_attribute_type(qs, _, value):
return qs.filter(type=value)
+def search_attribute_values(qs, value):
+ name_slug_qs = Q(name__ilike=value) | Q(slug__ilike=value)
+ return qs.filter(name_slug_qs)
+
+
class AttributeValueFilter(django_filters.FilterSet):
search = django_filters.CharFilter(method="filter_search")
ids = GlobalIDMultipleChoiceFilter(field_name="id")
@@ -103,11 +109,10 @@ class AttributeValueFilter(django_filters.FilterSet):
@classmethod
def filter_search(cls, queryset, _name, value):
+ """Filter attribute values by name or slug."""
if not value:
return queryset
- name_slug_qs = Q(name__ilike=value) | Q(slug__ilike=value)
-
- return queryset.filter(name_slug_qs)
+ return search_attribute_values(queryset, value)
class AttributeFilter(MetadataFilterBase):
@@ -296,3 +301,32 @@ class AttributeWhereInput(WhereInputObjectType):
filterset_class = AttributeWhere
description = "Where filtering options."
doc_category = DOC_CATEGORY_ATTRIBUTES
+
+
+class AttributeValueWhere(WhereFilterSet):
+ ids = GlobalIDMultipleChoiceWhereFilter(method=filter_by_ids("AttributeValue"))
+ name = OperationObjectTypeWhereFilter(
+ input_class=StringFilterInput, method="filter_by_name"
+ )
+ slug = OperationObjectTypeWhereFilter(
+ input_class=StringFilterInput, method="filter_by_slug"
+ )
+
+ class Meta:
+ model = AttributeValue
+ fields = []
+
+ @staticmethod
+ def filter_by_name(qs, name, value):
+ return filter_where_by_value_field(qs, "name", value)
+
+ @staticmethod
+ def filter_by_slug(qs, name, value):
+ return filter_where_by_value_field(qs, "slug", value)
+
+
+class AttributeValueWhereInput(WhereInputObjectType):
+ class Meta:
+ filterset_class = AttributeValueWhere
+ description = "Where filtering options for attribute values."
+ doc_category = DOC_CATEGORY_ATTRIBUTES
diff --git a/saleor/graphql/attribute/tests/queries/test_attribute_where.py b/saleor/graphql/attribute/tests/queries/test_attribute_where.py
index 05034fd368..9859b901a4 100644
--- a/saleor/graphql/attribute/tests/queries/test_attribute_where.py
+++ b/saleor/graphql/attribute/tests/queries/test_attribute_where.py
@@ -4,7 +4,7 @@ import graphene
import pytest
from .....attribute import AttributeInputType, AttributeType
-from .....attribute.models import Attribute
+from .....attribute.models import Attribute, AttributeValue
from .....attribute.utils import associate_attribute_values_to_instance
from .....core.units import MeasurementUnits
from .....product import ProductTypeKind
@@ -1832,3 +1832,167 @@ def test_search_attributes_on_root_level(
assert len(nodes) == len(indexes)
returned_attrs = {node["node"]["slug"] for node in nodes}
assert returned_attrs == {attributes[index].slug for index in indexes}
+
+
+ATTRIBUTE_VALUES_FILTER_QUERY = """
+query($id: ID!, $where: AttributeValueWhereInput, $search: String) {
+ attribute(id: $id) {
+ name
+ slug
+ choices(first: 10, where: $where, search: $search) {
+ edges {
+ node {
+ name
+ slug
+ }
+ }
+ }
+ }
+}
+"""
+
+
+def test_attributes_filter_by_choices_ids(api_client, color_attribute):
+ # given
+ choices = 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]]
+ value_ids = [
+ graphene.Node.to_global_id("AttributeValue", value.pk)
+ for value in lookup_values
+ ]
+
+ variables = {
+ "id": graphene.Node.to_global_id("Attribute", color_attribute.pk),
+ "where": {"ids": value_ids},
+ }
+
+ # when
+ response = api_client.post_graphql(ATTRIBUTE_VALUES_FILTER_QUERY, variables)
+
+ # then
+ data = get_graphql_content(response)
+ choices = data["data"]["attribute"]["choices"]["edges"]
+ assert len(choices) == len(lookup_values)
+ returned_choices = {node["node"]["slug"] for node in choices}
+ assert returned_choices == {value.slug for value in lookup_values}
+
+
+ ("where", "indexes"),
+ [
+ ({"eq": "choice-1"}, [0]),
+ ({"eq": "non-existent-choice"}, []),
+ ({"oneOf": ["choice-1", "choice-2"]}, [0, 1]),
+ ({"oneOf": ["non-existent-choice"]}, []),
+ ({"oneOf": []}, []),
+ ({"oneOf": None}, []),
+ ({"eq": None}, []),
+ ],
+)
+def test_attributes_filter_by_choices_slug(where, indexes, api_client, color_attribute):
+ # given
+ 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),
+ ]
+ )
+
+ variables = {
+ "id": graphene.Node.to_global_id("Attribute", color_attribute.pk),
+ "where": {"slug": where},
+ }
+
+ # when
+ response = api_client.post_graphql(ATTRIBUTE_VALUES_FILTER_QUERY, variables)
+
+ # then
+ data = get_graphql_content(response)
+ choices = data["data"]["attribute"]["choices"]["edges"]
+ assert len(choices) == len(indexes)
+ returned_choices = {node["node"]["slug"] for node in choices}
+ assert returned_choices == {values[index].slug for index in indexes}
+
+
+ ("where", "indexes"),
+ [
+ ({"eq": "Choice 1"}, [0]),
+ ({"eq": "Non-existent Choice"}, []),
+ ({"oneOf": ["Choice 1", "Choice 2"]}, [0, 1]),
+ ({"oneOf": ["Non-existent Choice"]}, []),
+ ({"oneOf": []}, []),
+ ({"oneOf": None}, []),
+ ({"eq": None}, []),
+ ],
+)
+def test_attributes_filter_by_choices_name(where, indexes, api_client, color_attribute):
+ # given
+ 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),
+ ]
+ )
+
+ variables = {
+ "id": graphene.Node.to_global_id("Attribute", color_attribute.pk),
+ "where": {"name": where},
+ }
+
+ # when
+ response = api_client.post_graphql(ATTRIBUTE_VALUES_FILTER_QUERY, variables)
+
+ # then
+ data = get_graphql_content(response)
+ choices = data["data"]["attribute"]["choices"]["edges"]
+ assert len(choices) == len(indexes)
+ returned_choices = {node["node"]["name"] for node in choices}
+ assert returned_choices == {values[index].name for index in indexes}
+
+
+ ("search", "indexes"),
+ [
+ ("choice", [0, 1, 2]),
+ ("Choice", [0, 1, 2]),
+ ("choice-1", [0]),
+ ("Choice 2", [1]),
+ ("Choice 3", [2]),
+ ("Non-existent", []),
+ ],
+)
+def test_attributes_filter_by_choices_search(
+ search, indexes, api_client, color_attribute
+):
+ # given
+ 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),
+ ]
+ )
+
+ variables = {
+ "id": graphene.Node.to_global_id("Attribute", color_attribute.pk),
+ "search": search,
+ }
+
+ # when
+ response = api_client.post_graphql(ATTRIBUTE_VALUES_FILTER_QUERY, variables)
+
+ # then
+ data = get_graphql_content(response)
+ choices = data["data"]["attribute"]["choices"]["edges"]
+ assert len(choices) == len(indexes)
+ returned_choices = {node["node"]["name"] for node in choices}
+ assert returned_choices == {values[index].name for index in indexes}
diff --git a/saleor/graphql/attribute/types.py b/saleor/graphql/attribute/types.py
index 25ec618a00..a8178cdf66 100644
--- a/saleor/graphql/attribute/types.py
+++ b/saleor/graphql/attribute/types.py
@@ -46,7 +46,11 @@ from ..translations.types import AttributeTranslation, AttributeValueTranslation
from .dataloaders import AttributesByAttributeId
from .descriptions import AttributeDescriptions, AttributeValueDescriptions
from .enums import AttributeEntityTypeEnum, AttributeInputTypeEnum, AttributeTypeEnum
-from .filters import AttributeValueFilterInput
+from .filters import (
+ AttributeValueFilterInput,
+ AttributeValueWhereInput,
+ search_attribute_values,
+)
from .sorters import AttributeChoicesSortingInput
from .utils import AttributeAssignmentMixin
@@ -241,8 +245,15 @@ class Attribute(ChannelContextType[models.Attribute]):
AttributeValueCountableConnection,
sort_by=AttributeChoicesSortingInput(description="Sort attribute choices."),
filter=AttributeValueFilterInput(
- description="Filtering options for attribute choices."
+ description=(
+ f"Filtering options for attribute choices. {DEPRECATED_IN_3X_INPUT} "
+ "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,
)
@@ -356,6 +367,9 @@ class Attribute(ChannelContextType[models.Attribute]):
else:
qs = models.AttributeValue.objects.none()
+ if search := kwargs.pop("search", None):
+ qs = search_attribute_values(qs, search)
+
channel_context_qs = ChannelQsContext(qs=qs, channel_slug=root.channel_slug)
channel_context_qs = filter_connection_queryset(
channel_context_qs, kwargs, allow_replica=info.context.allow_replica
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index 7e8ecae6f3..1c886cc4fb 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -6045,7 +6045,21 @@ type Attribute implements Node & ObjectWithMetadata @doc(category: "Attributes")
sortBy: AttributeChoicesSortingInput
"""Filtering options for attribute choices."""
- filter: AttributeValueFilterInput
+ filter: AttributeValueFilterInput @deprecated(reason: "Use where filter instead.")
+
+ """
+ Where filtering options for attribute choices.
+
+ Added in Saleor 3.22.
+ """
+ where: AttributeValueWhereInput
+
+ """
+ Search attribute choices.
+
+ Added in Saleor 3.22.
+ """
+ search: String
"""Return the elements in the list that come before the specified cursor."""
before: String
@@ -7429,6 +7443,19 @@ input AttributeValueFilterInput @doc(category: "Attributes") {
slugs: [String!]
}
+"""Where filtering options for attribute values."""
+input AttributeValueWhereInput @doc(category: "Attributes") {
+ ids: [ID!]
+ name: StringFilterInput
+ slug: StringFilterInput
+
+ """List of conditions that must be met."""
+ AND: [AttributeValueWhereInput!]
+
+ """A list of conditions of which at least one must be met."""
+ OR: [AttributeValueWhereInput!]
+}
+
type ProductTypeCountableConnection @doc(category: "Products") {
"""Pagination data for this connection."""
pageInfo: PageInfo!