Skip to content

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

Add stocks dataloader

fowczrekd1352af6de3b
diff --git a/saleor/graphql/product/tests/benchmark/test_variant_stocks.py b/saleor/graphql/product/tests/benchmark/test_variant_stocks.py
index 9003b98215..56298f9fc2 100644
--- a/saleor/graphql/product/tests/benchmark/test_variant_stocks.py
+++ b/saleor/graphql/product/tests/benchmark/test_variant_stocks.py
@@ -186,3 +186,43 @@ def test_product_variants_stocks_delete(
== variant.stocks.count()
== stocks_count - 1
)
+
+
[email protected]_queries(autouse=False)
+def test_query_product_variants_stocks(
+ staff_api_client, variant, warehouse, permission_manage_products, count_queries
+):
+ query = """
+ query getStocks($id: ID!){
+ productVariant(id: $id){
+ id
+ stocks{
+ quantity
+ }
+ }
+ }
+ """
+
+ variant_id = graphene.Node.to_global_id("ProductVariant", variant.pk)
+ second_warehouse = Warehouse.objects.get(pk=warehouse.pk)
+ second_warehouse.slug = "second warehouse"
+ second_warehouse.pk = None
+ second_warehouse.save()
+
+ Stock.objects.bulk_create(
+ [
+ Stock(product_variant=variant, warehouse=warehouse, quantity=10),
+ Stock(product_variant=variant, warehouse=second_warehouse, quantity=140),
+ ]
+ )
+
+ variables = {"id": variant_id}
+ response = staff_api_client.post_graphql(
+ query,
+ variables,
+ permissions=[permission_manage_products],
+ )
+ content = get_graphql_content(response)
+ data = content["data"]["productVariant"]
+ assert len(data["stocks"]) == variant.stocks.count()
diff --git a/saleor/graphql/product/types/products.py b/saleor/graphql/product/types/products.py
index 88ed5463d6..9ab596cbeb 100644
--- a/saleor/graphql/product/types/products.py
+++ b/saleor/graphql/product/types/products.py
@@ -68,6 +68,7 @@ from ...utils import (
from ...utils.filters import reporting_period_to_date
from ...warehouse.dataloaders import (
AvailableQuantityByProductVariantIdAndCountryCodeLoader,
+ StocksWithAvailableQuantityByProductVariantIdAndCountryCodeLoader,
)
from ...warehouse.types import Stock
from ..dataloaders import (
@@ -265,9 +266,9 @@ class ProductVariant(ChannelContextTypeWithMetadata, CountableDjangoObjectType):
address, info.context.site.settings.company_address
)
- if not country_code:
- return root.node.stocks.annotate_available_quantity()
- return root.node.stocks.for_country(country_code).annotate_available_quantity()
+ return StocksWithAvailableQuantityByProductVariantIdAndCountryCodeLoader(
+ info.context
+ ).load((root.node.id, country_code))
@staticmethod
def resolve_quantity_available(
diff --git a/saleor/graphql/warehouse/dataloaders.py b/saleor/graphql/warehouse/dataloaders.py
index 4fcd9f690e..91279d7043 100644
--- a/saleor/graphql/warehouse/dataloaders.py
+++ b/saleor/graphql/warehouse/dataloaders.py
@@ -20,7 +20,7 @@ class AvailableQuantityByProductVariantIdAndCountryCodeLoader(
or the maximum allowed checkout quantity, whichever is lower.
"""
- context_key = "stock_by_productvariant_and_country"
+ context_key = "available_quantity_by_productvariant_and_country"
def batch_load(self, keys):
# Split the list of keys by country first. A typical query will only touch
@@ -87,3 +87,56 @@ class AvailableQuantityByProductVariantIdAndCountryCodeLoader(
)
for variant_id in variant_ids
]
+
+
+class StocksWithAvailableQuantityByProductVariantIdAndCountryCodeLoader(
+ DataLoader[VariantIdAndCountryCode, Iterable[Stock]]
+):
+ """Return stocks with available quantity based on variant ID and country code.
+
+ For each country code, for each shipping zone supporting that country,
+ return stocks with maximum available quantity.
+ """
+
+ context_key = "stocks_with_available_quantity_by_productvariant_and_country"
+
+ def batch_load(self, keys):
+ # Split the list of keys by country first. A typical query will only touch
+ # a handful of unique countries but may access thousands of product variants
+ # so it's cheaper to execute one query per country.
+ variants_by_country: DefaultDict[CountryCode, List[int]] = defaultdict(list)
+ for variant_id, country_code in keys:
+ variants_by_country[country_code].append(variant_id)
+
+ # For each country code execute a single query for all product variants.
+ stocks_by_variant_and_country: DefaultDict[
+ VariantIdAndCountryCode, Iterable[Stock]
+ ] = defaultdict(list)
+ for country_code, variant_ids in variants_by_country.items():
+ variant_ids_stocks = self.batch_load_country(country_code, variant_ids)
+ for variant_id, stocks in variant_ids_stocks:
+ stocks_by_variant_and_country[(variant_id, country_code)].extend(stocks)
+
+ return [stocks_by_variant_and_country[key] for key in keys]
+
+ def batch_load_country(
+ self, country_code: CountryCode, variant_ids: Iterable[int]
+ ) -> Iterable[Tuple[int, List[Stock]]]:
+ stocks = Stock.objects.filter(product_variant_id__in=variant_ids)
+ if country_code:
+ stocks = stocks.filter(
+ warehouse__shipping_zones__countries__contains=country_code
+ )
+ stocks = stocks.annotate_available_quantity()
+
+ stocks_by_variant_id_map: DefaultDict[int, List[Stock]] = defaultdict(list)
+ for stock in stocks:
+ stocks_by_variant_id_map[stock.product_variant_id].append(stock)
+
+ return [
+ (
+ variant_id,
+ stocks_by_variant_id_map[variant_id],
+ )
+ for variant_id in variant_ids
+ ]