Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Extend product variants where filter (#17918)
Iga Karbowiak5d692d80e2c8
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex f3c50c593e..7ee792c523 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -72,6 +72,7 @@ All notable, unreleased changes to this project will be documented in this file.- `attributes`- `customers`- `products`+ - `productVariants`- `orders`- `draftOrders`- `productType.availableAttributes`diff --git a/saleor/graphql/product/filters.py b/saleor/graphql/product/filters.pyindex 76f90287bd..6d33b9b093 100644--- a/saleor/graphql/product/filters.py+++ b/saleor/graphql/product/filters.py@@ -74,6 +74,7 @@ from ..utils.filters import (filter_slug_list,filter_where_by_id_field,filter_where_by_numeric_field,+ filter_where_by_range_field,filter_where_by_value_field,filter_where_range_field_with_conditions,)@@ -1337,11 +1338,29 @@ class ProductVariantFilter(MetadataFilterBase):class ProductVariantWhere(MetadataWhereFilterBase):ids = GlobalIDMultipleChoiceWhereFilter(method=filter_by_ids("ProductVariant"))+ sku = ObjectTypeWhereFilter(+ input_class=StringFilterInput,+ method="filter_product_sku",+ help_text="Filter by product SKU.",+ )+ updated_at = ObjectTypeWhereFilter(+ input_class=DateTimeRangeInput,+ method="filter_updated_at",+ help_text="Filter by when was the most recent update.",+ )class Meta:model = ProductVariantfields = []+ @staticmethod+ def filter_product_sku(qs, _, value):+ return filter_where_by_value_field(qs, "sku", value)++ @staticmethod+ def filter_updated_at(qs, _, value):+ return filter_where_by_range_field(qs, "updated_at", value)+class CollectionFilter(MetadataFilterBase):published = EnumFilter(diff --git a/saleor/graphql/product/schema.py b/saleor/graphql/product/schema.pyindex 0a62b84f98..c3fe17ce3f 100644--- a/saleor/graphql/product/schema.py+++ b/saleor/graphql/product/schema.py@@ -1,8 +1,10 @@import graphene+from django.db.models import Exists, OuterReffrom promise import Promisefrom ...permission.enums import ProductPermissionsfrom ...permission.utils import has_one_of_permissions+from ...product import modelsfrom ...product.models import ALL_PRODUCTS_PERMISSIONSfrom ...product.search import search_productsfrom ..channel.dataloaders import ChannelBySlugLoader@@ -12,6 +14,7 @@ from ..core.connection import create_connection_slice, filter_connection_querysefrom ..core.context import ChannelContext, ChannelQsContextfrom ..core.descriptions import (ADDED_IN_321,+ ADDED_IN_322,DEFAULT_DEPRECATION_REASON,DEPRECATED_IN_3X_INPUT,)@@ -27,6 +30,7 @@ from ..core.tracing import traced_resolverfrom ..core.types import NonNullListfrom ..core.utils import from_global_id_or_errorfrom ..core.validators import validate_one_of_args_is_in_query+from ..shop.resolvers import get_database_connection_namefrom ..translations.mutations import (CategoryTranslate,CollectionTranslate,@@ -264,8 +268,8 @@ class ProductQueries(graphene.ObjectType):ProductCountableConnection,filter=ProductFilterInput(description=(- f"Filtering options for products. {DEPRECATED_IN_3X_INPUT} "- "Use `where` filter instead."+ f"Filtering options for products. {DEPRECATED_IN_3X_INPUT}"+ " Use `where` filter instead.")),where=ProductWhereInput(description="Where filtering options for products."),@@ -329,11 +333,15 @@ class ProductQueries(graphene.ObjectType):description="Slug of a channel for which the data should be returned."),filter=ProductVariantFilterInput(- description="Filtering options for product variant."+ description=(+ f"Filtering options for product variants. {DEPRECATED_IN_3X_INPUT}"+ " Use `where` filter instead."+ )),where=ProductVariantWhereInput(description="Where filtering options for product variants."),+ search=graphene.String(description="Search product variants." + ADDED_IN_322),sort_by=ProductVariantSortingInput(description="Sort products variants."),description=("List of product variants. Requires one of the following permissions to "@@ -627,6 +635,8 @@ class ProductQueries(graphene.ObjectType):allow_replica=info.context.allow_replica)+ search = kwargs.get("search")+def _resolve_product_variants(channel_obj):qs = resolve_product_variants(info,@@ -635,6 +645,17 @@ class ProductQueries(graphene.ObjectType):limited_channel_access=limited_channel_access,requestor=requestor,)+ if search:+ products = search_products(+ models.Product.objects.using(+ get_database_connection_name(info.context)+ ),+ search,+ )+ variant_qs = qs.qs.filter(+ Exists(products.filter(id=OuterRef("product_id")))+ )+ qs = ChannelQsContext(qs=variant_qs, channel_slug=qs.channel_slug)kwargs["channel"] = qs.channel_slugqs = filter_connection_queryset(qs, kwargs, allow_replica=info.context.allow_replicadiff --git a/saleor/graphql/product/tests/queries/test_product_query.py b/saleor/graphql/product/tests/queries/test_product_query.pyindex 32acb5446c..d894325bbd 100644--- a/saleor/graphql/product/tests/queries/test_product_query.py+++ b/saleor/graphql/product/tests/queries/test_product_query.py@@ -2994,3 +2994,46 @@ def test_product_tax_class_query_by_staff(staff_api_client, product, channel_USDassert data["product"]assert data["product"]["id"]assert data["product"]["taxClass"]["id"]+++QUERY_FETCH_PRODUCT_VARIANTS = """+ query ($id: ID!, $channel: String, $where: ProductVariantWhereInput) {+ product(id: $id, channel: $channel) {+ id+ productVariants(first: 10, where: $where) {+ edges {+ node {+ id+ name+ sku+ }+ }+ }+ }+ }+"""+++def test_query_product_variants_with_where(+ user_api_client, product_variant_list, channel_USD+):+ # given+ product = product_variant_list[0].product+ sku_value = product_variant_list[0].sku+ product_id = graphene.Node.to_global_id("Product", product.id)++ variables = {+ "id": product_id,+ "channel": channel_USD.slug,+ "where": {"sku": {"eq": sku_value}},+ }++ # when+ response = user_api_client.post_graphql(QUERY_FETCH_PRODUCT_VARIANTS, variables)++ # then+ content = get_graphql_content(response)+ variants = content["data"]["product"]["productVariants"]["edges"]++ assert len(variants) == 1+ assert variants[0]["node"]["sku"] == sku_valuediff --git a/saleor/graphql/product/tests/queries/test_product_variants_query.py b/saleor/graphql/product/tests/queries/test_product_variants_query.pyindex abfde0b640..c038254261 100644--- a/saleor/graphql/product/tests/queries/test_product_variants_query.py+++ b/saleor/graphql/product/tests/queries/test_product_variants_query.py@@ -1,6 +1,8 @@import graphene+import pytestfrom .....product.models import Product, ProductVariant+from .....product.search import update_products_search_vectorfrom ....tests.utils import get_graphql_content, get_graphql_content_from_response@@ -269,3 +271,75 @@ def test_product_variants_visible_in_listings_by_app_with_perm()assert data["totalCount"] == product_count+++QUERY_SEARCH_PRODUCT_VARIANTS = """+ query searchProductVariants($search: String, $channel: String) {+ productVariants(search: $search, first: 10, channel: $channel) {+ edges {+ node {+ id+ name+ sku+ }+ }+ }+ }+"""+++ ("search_query", "expected_indexes"),+ [("VariantName", [0, 1, 2]), ("SKU1", [1]), ("SKU2", [2]), ("Invalid", [])],+)+def test_search_product_variants_by_variant_name_and_sku(+ search_query, expected_indexes, user_api_client, product_list, channel_USD+):+ # given+ variants_list = list(ProductVariant.objects.all())+ for index, variant in enumerate(variants_list):+ variant.sku = f"SKU{index}"+ variant.name = "VariantName"+ variant.save()++ update_products_search_vector(Product.objects.values_list("id", flat=True))++ # when+ variables = {"search": search_query, "channel": channel_USD.slug}+ response = user_api_client.post_graphql(QUERY_SEARCH_PRODUCT_VARIANTS, variables)++ # then+ content = get_graphql_content(response)+ variants = content["data"]["productVariants"]["edges"]+ assert len(variants) == len(expected_indexes)+ skus = {node["node"]["sku"] for node in variants}+ assert skus == {variants_list[index].sku for index in expected_indexes}+++ ("search_query", "expected_indexes"),+ [("ProductName", [0, 1]), ("anotherName", [2]), ("Invalid", [])],+)+def test_search_products_by_product_name(+ search_query, expected_indexes, user_api_client, product_list, channel_USD+):+ # given+ variants_list = sorted(ProductVariant.objects.all(), key=lambda x: x.product_id)++ for product in product_list[:2]:+ product.name = "ProductName"+ product_list[2].name = "anotherName"+ Product.objects.bulk_update(product_list, ["name"])++ update_products_search_vector(Product.objects.values_list("id", flat=True))++ # when+ variables = {"search": search_query, "channel": channel_USD.slug}+ response = user_api_client.post_graphql(QUERY_SEARCH_PRODUCT_VARIANTS, variables)++ # then+ content = get_graphql_content(response)+ products = content["data"]["productVariants"]["edges"]+ assert len(products) == len(expected_indexes)+ skus = {node["node"]["sku"] for node in products}+ assert skus == {variants_list[index].sku for index in expected_indexes}diff --git a/saleor/graphql/product/tests/queries/test_product_variants_query_with_where.py b/saleor/graphql/product/tests/queries/test_product_variants_query_with_where.pyindex 6d65472eab..857c6ee9db 100644--- a/saleor/graphql/product/tests/queries/test_product_variants_query_with_where.py+++ b/saleor/graphql/product/tests/queries/test_product_variants_query_with_where.py@@ -1,5 +1,11 @@+import datetime+import graphene+import pytest+from django.utils import timezone+from freezegun import freeze_time+from .....product.models import ProductVariantfrom ....tests.utils import get_graphql_contentPRODUCT_VARIANTS_WHERE_QUERY = """@@ -67,3 +73,102 @@ def test_product_variant_filter_by_ids_empty_list(data = get_graphql_content(response)variants = data["data"]["productVariants"]["edges"]assert len(variants) == 0+++ ("where", "indexes"),+ [+ (+ {+ "gte": (timezone.now() - datetime.timedelta(days=25)).isoformat(),+ "lte": (timezone.now() - datetime.timedelta(days=2)).isoformat(),+ },+ [0, 1],+ ),+ (+ {+ "lte": (timezone.now() - datetime.timedelta(days=25)).isoformat(),+ },+ [],+ ),+ (+ {+ "lte": (timezone.now() - datetime.timedelta(hours=10)).isoformat(),+ },+ [0, 1],+ ),+ (None, []),+ ({"gte": None}, []),+ ({"lte": None}, []),+ ({"lte": None, "gte": None}, []),+ ({}, []),+ ],+)+def test_product_variant_filter_by_updated_at(+ where,+ indexes,+ product_variant_list,+ api_client,+ channel_USD,+):+ # given+ with freeze_time((timezone.now() - datetime.timedelta(days=15)).isoformat()):+ product_variant_list[0].save(update_fields=["updated_at"])++ with freeze_time((timezone.now() - datetime.timedelta(days=3)).isoformat()):+ product_variant_list[1].save(update_fields=["updated_at"])++ # variant available only in channel PLN+ with freeze_time((timezone.now() - datetime.timedelta(days=1)).isoformat()):+ product_variant_list[2].save(update_fields=["updated_at"])++ variables = {"channel": channel_USD.slug, "where": {"updatedAt": where}}++ # when+ response = api_client.post_graphql(PRODUCT_VARIANTS_WHERE_QUERY, variables)++ # then+ content = get_graphql_content(response)+ variants = content["data"]["productVariants"]["edges"]+ assert len(variants) == len(indexes)+ skus = {node["node"]["sku"] for node in variants}+ assert skus == {product_variant_list[index].sku for index in indexes}+++ ("where", "indexes"),+ [+ ({"eq": "SKU1"}, [0]),+ ({"eq": "SKU2"}, [1]),+ ({"eq": "SKU_NON_EXISTENT"}, []),+ ({"oneOf": ["SKU1", "SKU2"]}, [0, 1]),+ ({"oneOf": ["SKU1", "SKU_NON_EXISTENT"]}, [0]),+ ({"oneOf": []}, []),+ (None, []),+ ({}, []),+ ],+)+def test_product_variant_filter_by_sku(+ where,+ indexes,+ product_variant_list,+ api_client,+ channel_USD,+):+ # given+ product_variant_list[0].sku = "SKU1"+ product_variant_list[1].sku = "SKU2"+ product_variant_list[2].sku = "SKU3"+ ProductVariant.objects.bulk_update(product_variant_list, ["sku"])++ variables = {"channel": channel_USD.slug, "where": {"sku": where}}++ # when+ response = api_client.post_graphql(PRODUCT_VARIANTS_WHERE_QUERY, variables)++ # then+ content = get_graphql_content(response)+ variants = content["data"]["productVariants"]["edges"]+ assert len(variants) == len(indexes)+ skus = {node["node"]["sku"] for node in variants}+ assert skus == {product_variant_list[index].sku for index in indexes}diff --git a/saleor/graphql/product/tests/test_variant_with_filtering.py b/saleor/graphql/product/tests/test_variant_with_filtering.pyindex 0644bf04ab..b35647723a 100644--- a/saleor/graphql/product/tests/test_variant_with_filtering.py+++ b/saleor/graphql/product/tests/test_variant_with_filtering.py@@ -5,6 +5,7 @@ from django.utils import timezonefrom freezegun import freeze_timefrom ....product.models import Product, ProductVariant+from ....product.search import update_products_search_vectorfrom ...tests.utils import get_graphql_contentQUERY_VARIANTS_FILTER = """@@ -115,6 +116,7 @@ def products_for_variant_filtering(product_type, category):),])+ update_products_search_vector([product.id for product in products])return productsdiff --git a/saleor/graphql/product/types/categories.py b/saleor/graphql/product/types/categories.pyindex 6a264df9b8..bd96e28628 100644--- a/saleor/graphql/product/types/categories.py+++ b/saleor/graphql/product/types/categories.py@@ -19,7 +19,7 @@ from ...core.connection import (filter_connection_queryset,)from ...core.context import ChannelQsContext, get_database_connection_name-from ...core.descriptions import RICH_CONTENT+from ...core.descriptions import DEPRECATED_IN_3X_INPUT, RICH_CONTENTfrom ...core.doc_category import DOC_CATEGORY_PRODUCTSfrom ...core.federation import federated_entity, resolve_federation_referencesfrom ...core.fields import ConnectionField, FilterConnectionField, JSONString@@ -65,7 +65,8 @@ class Category(ModelObjectType[models.Category]):ProductCountableConnection,filter=ProductFilterInput(description=(- "Filtering options for products. {DEPRECATED_IN_3X_INPUT} Use `where` filter instead."+ f"Filtering options for products. {DEPRECATED_IN_3X_INPUT} "+ "Use `where` filter instead.")),where=ProductWhereInput(description="Where filtering options for products."),diff --git a/saleor/graphql/product/types/products.py b/saleor/graphql/product/types/products.pyindex ba1d800f68..663f5464d6 100644--- a/saleor/graphql/product/types/products.py+++ b/saleor/graphql/product/types/products.py@@ -963,7 +963,10 @@ class Product(ChannelContextType[models.Product]):product_variants = FilterConnectionField(ProductVariantCountableConnection,filter=ProductVariantFilterInput(- description="Filtering options for product variant."+ description=(+ f"Filtering options for product variant. {DEPRECATED_IN_3X_INPUT} "+ "Use `where` filter instead."+ )),where=ProductVariantWhereInput(description="Where filtering options for product variants."diff --git a/saleor/graphql/schema.graphql b/saleor/graphql/schema.graphqlindex e4fb5fafcf..7e8ecae6f3 100644--- a/saleor/graphql/schema.graphql+++ b/saleor/graphql/schema.graphql@@ -555,12 +555,19 @@ type Query {"""Slug of a channel for which the data should be returned."""channel: String- """Filtering options for product variant."""- filter: ProductVariantFilterInput+ """Filtering options for product variants."""+ filter: ProductVariantFilterInput @deprecated(reason: "Use `where` filter instead.")"""Where filtering options for product variants."""where: ProductVariantWhereInput+ """+ Search product variants.++ Added in Saleor 3.22.+ """+ search: String+"""Sort products variants."""sortBy: ProductVariantSortingInput@@ -5698,7 +5705,7 @@ type Product implements Node & ObjectWithMetadata @doc(category: "Products") {"""productVariants("""Filtering options for product variant."""- filter: ProductVariantFilterInput+ filter: ProductVariantFilterInput @deprecated(reason: "Use `where` filter instead.")"""Where filtering options for product variants."""where: ProductVariantWhereInput@@ -7547,10 +7554,8 @@ type Category implements Node & ObjectWithMetadata @doc(category: "Products") {List of products in the category. Requires the following permissions to include the unpublished items: MANAGE_ORDERS, MANAGE_DISCOUNTS, MANAGE_PRODUCTS."""products(- """- Filtering options for products. {DEPRECATED_IN_3X_INPUT} Use `where` filter instead.- """- filter: ProductFilterInput+ """Filtering options for products."""+ filter: ProductFilterInput @deprecated(reason: "Use `where` filter instead.")"""Where filtering options for products."""where: ProductWhereInput@@ -8200,6 +8205,12 @@ input ProductVariantWhereInput @doc(category: "Products") {metadata: [MetadataFilter!]ids: [ID!]+ """Filter by product SKU."""+ sku: StringFilterInput++ """Filter by when was the most recent update."""+ updatedAt: DateTimeRangeInput+"""List of conditions that must be met."""AND: [ProductVariantWhereInput!]diff --git a/saleor/product/migrations/0201_productvariant_variant_gin.py b/saleor/product/migrations/0201_productvariant_variant_gin.pynew file mode 100644index 0000000000..d456e3348b--- /dev/null+++ b/saleor/product/migrations/0201_productvariant_variant_gin.py@@ -0,0 +1,24 @@+# Generated by Django 5.2.1 on 2025-07-03 12:21++from django.contrib.postgres.indexes import GinIndex+from django.contrib.postgres.operations import AddIndexConcurrently+from django.db import migrations+++class Migration(migrations.Migration):+ atomic = False++ dependencies = [+ ("product", "0200_merge_20250527_1210"),+ ]++ operations = [+ AddIndexConcurrently(+ model_name="productvariant",+ index=GinIndex(+ fields=["name", "sku"],+ name="variant_gin",+ opclasses=["gin_trgm_ops", "gin_trgm_ops"],+ ),+ ),+ ]diff --git a/saleor/product/models.py b/saleor/product/models.pyindex f50d73feb1..12aff54aa6 100644--- a/saleor/product/models.py+++ b/saleor/product/models.py@@ -375,6 +375,14 @@ class ProductVariant(SortableModel, ModelWithMetadata, ModelWithExternalReferencclass Meta(ModelWithMetadata.Meta):ordering = ("sort_order", "sku")app_label = "product"+ indexes = [+ *ModelWithMetadata.Meta.indexes,+ GinIndex(+ name="variant_gin",+ fields=["name", "sku"],+ opclasses=["gin_trgm_ops"] * 2,+ ),+ ]def __str__(self) -> str:return self.name or self.sku or f"ID:{self.pk}"