Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Optimize products stock availability filter (#8809)
Filip Owczarekdebdecd2be84
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 3cc2a08df0..10e41e2c73 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -22,6 +22,7 @@ All notable, unreleased changes to this project will be documented in this file.- Add `variant_selection` to `ProductAttributeAssign` operations - #8235 by @kuchichan- Add query complexity limit to GraphQL API - #8526 by rafalp- Add `quantity_limit_per_customer` field to ProductVariant #8405 by @kuchichan+- Optimize products stock availability filter - #8809 by @fowczarek# 3.0.0 [Unreleased]diff --git a/saleor/graphql/product/filters.py b/saleor/graphql/product/filters.pyindex 2a4b2882de..91f1660af6 100644--- a/saleor/graphql/product/filters.py+++ b/saleor/graphql/product/filters.py@@ -314,13 +314,14 @@ def filter_products_by_stock_availability(qs, stock_availability, channel_slug):)allocated_subquery = Subquery(queryset=allocations, output_field=IntegerField())- stocks = list(+ stocks = (Stock.objects.for_channel(channel_slug).filter(quantity__gt=Coalesce(allocated_subquery, 0))- .values_list("product_variant_id", flat=True)+ .values("product_variant_id"))-- variants = ProductVariant.objects.filter(pk__in=stocks).values("product_id")+ variants = ProductVariant.objects.filter(+ Exists(stocks.filter(product_variant_id=OuterRef("pk")))+ ).values("product_id")if stock_availability == StockAvailability.IN_STOCK:qs = qs.filter(Exists(variants.filter(product_id=OuterRef("pk"))))diff --git a/saleor/graphql/product/tests/test_product.py b/saleor/graphql/product/tests/test_product.pyindex 73f9bf4b86..4a14791014 100644--- a/saleor/graphql/product/tests/test_product.py+++ b/saleor/graphql/product/tests/test_product.py@@ -2603,15 +2603,10 @@ def test_products_query_with_filter_stock_availability_channel_without_shipping_query_products_with_filter,staff_api_client,product,- order_line,permission_manage_products,channel_USD,):channel_USD.shipping_zones.clear()- stock = product.variants.first().stocks.first()- Allocation.objects.create(- order_line=order_line, stock=stock, quantity_allocated=stock.quantity- )variables = {"filter": {"stockAvailability": "OUT_OF_STOCK"},"channel": channel_USD.slug,@@ -2620,8 +2615,10 @@ def test_products_query_with_filter_stock_availability_channel_without_shipping_response = staff_api_client.post_graphql(query_products_with_filter, variables)content = get_graphql_content(response)products = content["data"]["products"]["edges"]+ product_id = graphene.Node.to_global_id("Product", product.id)- assert len(products) == 0+ assert len(products) == 1+ assert products[0]["node"]["id"] == product_id@pytest.mark.parametrize(