Skip to content

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

Allow filtering attributes by value names (#17740)

Iga Karbowiak705a438bf0df
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 588c4b99bb..b8d98ed0d6 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,7 @@ All notable, unreleased changes to this project will be documented in this file.
### Breaking changes
### GraphQL API
+- Added support for filtering products by attribute value names. The `AttributeInput` now includes a `valueNames` field, enabling filtering by the names of attribute values, in addition to the existing filtering by value slugs.
- You can now filter and search orders using the new `where` and `search` fields on the `orders` query.
- Use `where` to define complex conditions with `AND`/`OR` logic and operators like `eq`, `oneOf`, `range`.
- Use `search` to perform full-text search across relevant fields.
diff --git a/saleor/graphql/attribute/types.py b/saleor/graphql/attribute/types.py
index fcf64e49c2..0970779981 100644
--- a/saleor/graphql/attribute/types.py
+++ b/saleor/graphql/attribute/types.py
@@ -15,6 +15,7 @@ from ..core.connection import (
)
from ..core.context import get_database_connection_name
from ..core.descriptions import (
+ ADDED_IN_322,
DEFAULT_DEPRECATION_REASON,
DEPRECATED_IN_3X_INPUT,
)
@@ -376,8 +377,24 @@ class SelectedAttribute(BaseObjectType):
class AttributeInput(BaseInputObjectType):
slug = graphene.String(required=True, description=AttributeDescriptions.SLUG)
+ value_names = NonNullList(
+ graphene.String,
+ required=False,
+ description=(
+ "Names corresponding to the attributeValues associated with the Attribute. "
+ "When specified, it filters the results to include only records with "
+ "one of the matching values."
+ )
+ + ADDED_IN_322,
+ )
values = NonNullList(
- graphene.String, required=False, description=AttributeValueDescriptions.SLUG
+ graphene.String,
+ required=False,
+ description=(
+ "Slugs identifying the attributeValues associated with the Attribute. "
+ "When specified, it filters the results to include only records with "
+ "one of the matching values."
+ ),
)
values_range = graphene.Field(
IntRangeInput,
diff --git a/saleor/graphql/product/filters.py b/saleor/graphql/product/filters.py
index 0371cb6ed5..cbdba06199 100644
--- a/saleor/graphql/product/filters.py
+++ b/saleor/graphql/product/filters.py
@@ -91,46 +91,58 @@ T_PRODUCT_FILTER_QUERIES = dict[int, list[int]]
def _clean_product_attributes_filter_input(
- filter_value, queries, database_connection_name
+ filter_values, field, queries, database_connection_name
):
attribute_slugs = []
- value_slugs = []
- for attr_slug, val_slugs in filter_value:
+ values = []
+
+ for attr_slug, field_value in filter_values:
attribute_slugs.append(attr_slug)
- value_slugs.extend(val_slugs)
+ values.extend(field_value)
+
attributes_slug_pk_map: dict[str, int] = {}
attributes_pk_slug_map: dict[int, str] = {}
- values_map: dict[str, dict[str, int]] = defaultdict(dict)
- for attr_slug, attr_pk in (
- Attribute.objects.using(database_connection_name)
- .filter(slug__in=attribute_slugs)
- .values_list("slug", "id")
- ):
+ attributes = Attribute.objects.using(database_connection_name).filter(
+ slug__in=attribute_slugs
+ )
+ for attr_slug, attr_pk in attributes.values_list("slug", "id"):
attributes_slug_pk_map[attr_slug] = attr_pk
attributes_pk_slug_map[attr_pk] = attr_slug
+ values_map = _populate_value_map(
+ database_connection_name, field, values, attributes, attributes_pk_slug_map
+ )
+
+ _update_queries(queries, filter_values, attributes_slug_pk_map, values_map)
+
+
+def _populate_value_map(
+ database_connection_name, field, values, attribute_qs, attributes_pk_slug_map
+):
+ value_maps: dict[str, dict[str, int]] = defaultdict(dict)
for (
attr_pk,
value_pk,
- value_slug,
+ field_value,
) in (
AttributeValue.objects.using(database_connection_name)
- .filter(slug__in=value_slugs, attribute_id__in=attributes_pk_slug_map.keys())
- .values_list("attribute_id", "pk", "slug")
+ .filter(Exists(attribute_qs.filter(pk=OuterRef("attribute_id"))))
+ .filter(**{f"{field}__in": values})
+ .values_list("attribute_id", "pk", field)
):
attr_slug = attributes_pk_slug_map[attr_pk]
- values_map[attr_slug][value_slug] = value_pk
+ value_maps[attr_slug][field_value] = value_pk
- # Convert attribute:value pairs into a dictionary where
- # attributes are keys and values are grouped in lists
- for attr_name, val_slugs in filter_value:
+ return value_maps
+
+
+def _update_queries(queries, filter_values, attributes_slug_pk_map, value_maps):
+ for attr_name, vals in filter_values:
if attr_name not in attributes_slug_pk_map:
raise ValueError(f"Unknown attribute name: {attr_name}")
attr_pk = attributes_slug_pk_map[attr_name]
attr_val_pk = [
- values_map[attr_name][val_slug]
- for val_slug in val_slugs
- if val_slug in values_map[attr_name]
+ value_maps[attr_name][val] for val in vals if val in value_maps[attr_name]
]
queries[attr_pk] += attr_val_pk
@@ -288,7 +300,8 @@ def filter_products_by_attributes_values_qs(qs, values_qs):
def filter_products_by_attributes(
qs,
- filter_values,
+ filter_slug_values,
+ filter_name_values,
filter_range_values,
filter_boolean_values,
date_range_list,
@@ -296,8 +309,14 @@ def filter_products_by_attributes(
):
queries: dict[int, list[int]] = defaultdict(list)
try:
- if filter_values:
- _clean_product_attributes_filter_input(filter_values, queries, qs.db)
+ if filter_slug_values:
+ _clean_product_attributes_filter_input(
+ filter_slug_values, "slug", queries, qs.db
+ )
+ if filter_name_values:
+ _clean_product_attributes_filter_input(
+ filter_name_values, "name", queries, qs.db
+ )
if filter_range_values:
_clean_product_attributes_range_filter_input(
filter_range_values, queries, qs.db
@@ -436,7 +455,8 @@ def filter_products_by_stock_availability(qs, stock_availability, channel_slug):
def _filter_attributes(qs, _, value):
if value:
- value_list = []
+ slug_value_list = []
+ name_value_list = []
boolean_list = []
value_range_list = []
date_range_list = []
@@ -445,7 +465,9 @@ def _filter_attributes(qs, _, value):
for v in value:
slug = v["slug"]
if "values" in v:
- value_list.append((slug, v["values"]))
+ slug_value_list.append((slug, v["values"]))
+ elif "value_names" in v:
+ name_value_list.append((slug, v["value_names"]))
elif "values_range" in v:
value_range_list.append((slug, v["values_range"]))
elif "date" in v:
@@ -457,7 +479,8 @@ def _filter_attributes(qs, _, value):
qs = filter_products_by_attributes(
qs,
- value_list,
+ slug_value_list,
+ name_value_list,
value_range_list,
boolean_list,
date_range_list,
@@ -938,7 +961,8 @@ def where_filter_attributes(qs, _, value):
if not value:
return qs.none()
- value_list = []
+ slug_value_list = []
+ name_value_list = []
boolean_list = []
value_range_list = []
date_range_list = []
@@ -947,7 +971,9 @@ def where_filter_attributes(qs, _, value):
for v in value:
slug = v["slug"]
if "values" in v:
- value_list.append((slug, v["values"]))
+ slug_value_list.append((slug, v["values"]))
+ elif "value_names" in v:
+ name_value_list.append((slug, v["value_names"]))
elif "values_range" in v:
value_range_list.append((slug, v["values_range"]))
elif "date" in v:
@@ -959,7 +985,8 @@ def where_filter_attributes(qs, _, value):
qs = filter_products_by_attributes(
qs,
- value_list,
+ slug_value_list,
+ name_value_list,
value_range_list,
boolean_list,
date_range_list,
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.py
index be91a8ffd0..ca6ee260b7 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
@@ -650,7 +650,7 @@ def test_product_filter_by_minimal_price(
assert returned_slugs == {product_list[index].slug for index in indexes}
-def test_products_filter_by_attributes(
+def test_products_filter_by_attributes_value_slug(
api_client,
product_list,
channel_USD,
@@ -696,6 +696,52 @@ def test_products_filter_by_attributes(
assert products[0]["node"]["name"] == product.name
+def test_products_filter_by_attributes_value_name(
+ api_client,
+ product_list,
+ channel_USD,
+):
+ # given
+ product_type = ProductType.objects.create(
+ name="Custom Type",
+ slug="custom-type",
+ has_variants=True,
+ is_shipping_required=True,
+ kind=ProductTypeKind.NORMAL,
+ )
+ attribute = Attribute.objects.create(slug="new_attr", name="Attr")
+ attribute.product_types.add(product_type)
+ attr_value = AttributeValue.objects.create(
+ attribute=attribute, name="First", slug="first"
+ )
+ product = product_list[0]
+ product.product_type = product_type
+ product.save()
+ associate_attribute_values_to_instance(
+ product,
+ {attribute.id: [attr_value]},
+ )
+
+ variables = {
+ "channel": channel_USD.slug,
+ "where": {
+ "attributes": [{"slug": attribute.slug, "valueNames": [attr_value.name]}],
+ },
+ }
+
+ # when
+ response = api_client.post_graphql(PRODUCTS_WHERE_QUERY, variables)
+ content = get_graphql_content(response)
+
+ # then
+ product_id = graphene.Node.to_global_id("Product", product.id)
+ products = content["data"]["products"]["edges"]
+
+ assert len(products) == 1
+ assert products[0]["node"]["id"] == product_id
+ assert products[0]["node"]["name"] == product.name
+
+
def test_products_filter_by_attributes_empty_list(
api_client,
product_list,
diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphql
index c895969f10..d391f7c986 100644
--- a/saleor/graphql/schema.graphql
+++ b/saleor/graphql/schema.graphql
@@ -6648,7 +6648,16 @@ input AttributeInput @doc(category: "Attributes") {
"""Internal representation of an attribute name."""
slug: String!
- """Internal representation of a value (unique per attribute)."""
+ """
+ Names corresponding to the attributeValues associated with the Attribute. When specified, it filters the results to include only records with one of the matching values.
+
+ Added in Saleor 3.22.
+ """
+ valueNames: [String!]
+
+ """
+ Slugs identifying the attributeValues associated with the Attribute. When specified, it filters the results to include only records with one of the matching values.
+ """
values: [String!]
"""The range that the returned values should be in."""