Skip to content

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

Optimize available quantity loader in 3.1 (#7873)

Filip Owczarek54b2e510c366
diff --git a/CHANGELOG.md b/CHANGELOG.md
index f4cfd381a0..412dba7999 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -136,6 +136,7 @@ All notable, unreleased changes to this project will be documented in this file.
- Deprecate `query` argument in `sales` and `vouchers` queries - #7806 by @maarcingebala
- Allow translating objects by translatable content ID - #7803 by @maarcingebala
- Add `page_type_id` when it's possible for `AttributeValue` translations webhook. - #7825 by @fowczarek
+- Optimize available quantity loader. - #7802 by @fowczarek
### Breaking
diff --git a/saleor/graphql/product/types/products.py b/saleor/graphql/product/types/products.py
index 336bc37e0f..6fbb9ad727 100644
--- a/saleor/graphql/product/types/products.py
+++ b/saleor/graphql/product/types/products.py
@@ -825,7 +825,6 @@ class Product(ChannelContextTypeWithMetadata, CountableDjangoObjectType):
return ImagesByProductIdLoader(info.context).load(root.node.id)
@staticmethod
- @traced_resolver
def resolve_variants(root: ChannelContext[models.Product], info, **_kwargs):
requestor = get_user_or_app_from_context(info.context)
is_staff = requestor_is_staff_member_or_app(requestor)
diff --git a/saleor/graphql/warehouse/dataloaders.py b/saleor/graphql/warehouse/dataloaders.py
index 4f5e4f1ab6..05d55c2bd8 100644
--- a/saleor/graphql/warehouse/dataloaders.py
+++ b/saleor/graphql/warehouse/dataloaders.py
@@ -3,8 +3,10 @@ from typing import DefaultDict, Iterable, List, Optional, Tuple
from uuid import UUID
from django.conf import settings
+from django.db.models import Exists, OuterRef
-from ...warehouse.models import Stock, Warehouse
+from ...channel.models import Channel
+from ...warehouse.models import ShippingZone, Stock, Warehouse
from ..account.dataloaders import AddressByIdLoader
from ..channel.dataloaders import ChannelBySlugLoader
from ..core.dataloaders import DataLoader
@@ -62,18 +64,39 @@ class AvailableQuantityByProductVariantIdCountryCodeAndChannelSlugLoader(
# get stocks only for warehouses assigned to the shipping zones
# that are available in the given channel
stocks = Stock.objects.filter(product_variant_id__in=variant_ids)
- if country_code:
- stocks = stocks.filter(
- warehouse__shipping_zones__countries__contains=country_code
- )
- if channel_slug:
- stocks = stocks.filter(
- warehouse__shipping_zones__channels__slug=channel_slug
+ WarehouseShippingZone = Warehouse.shipping_zones.through # type: ignore
+ warehouse_shipping_zones = WarehouseShippingZone.objects.all()
+ additional_warehouse_filter = False
+ if country_code or channel_slug:
+ additional_warehouse_filter = True
+ if country_code:
+ shipping_zones = ShippingZone.objects.filter(
+ countries__contains=country_code
+ ).values("pk")
+ warehouse_shipping_zones = warehouse_shipping_zones.filter(
+ Exists(shipping_zones.filter(pk=OuterRef("shippingzone_id")))
+ )
+ if channel_slug:
+ ShippingZoneChannel = Channel.shipping_zones.through # type: ignore
+ channels = Channel.objects.filter(slug=channel_slug).values("pk")
+ shipping_zone_channels = ShippingZoneChannel.objects.filter(
+ Exists(channels.filter(pk=OuterRef("channel_id")))
+ ).values("shippingzone_id")
+ warehouse_shipping_zones = warehouse_shipping_zones.filter(
+ Exists(
+ shipping_zone_channels.filter(
+ shippingzone_id=OuterRef("shippingzone_id")
+ )
+ )
+ )
+ warehouse_shipping_zones_map = defaultdict(list)
+ for warehouse_shipping_zone in warehouse_shipping_zones:
+ warehouse_shipping_zones_map[warehouse_shipping_zone.warehouse_id].append(
+ warehouse_shipping_zone.shippingzone_id
)
+ if additional_warehouse_filter:
+ stocks = stocks.filter(warehouse_id__in=warehouse_shipping_zones_map.keys())
stocks = stocks.annotate_available_quantity()
- stocks = stocks.values_list(
- "product_variant_id", "warehouse__shipping_zones", "available_quantity"
- )
# A single country code (or a missing country code) can return results from
# multiple shipping zones. We want to combine all quantities within a single
@@ -81,10 +104,16 @@ class AvailableQuantityByProductVariantIdCountryCodeAndChannelSlugLoader(
quantity_by_shipping_zone_by_product_variant: DefaultDict[
int, DefaultDict[int, int]
] = defaultdict(lambda: defaultdict(int))
- for variant_id, shipping_zone_id, quantity in stocks:
- quantity_by_shipping_zone_by_product_variant[variant_id][
- shipping_zone_id
- ] += quantity
+ for stock in stocks:
+ quantity = stock.available_quantity
+ variant_id = stock.product_variant_id
+ warehouse_id = stock.warehouse_id
+ shipping_zone_ids = warehouse_shipping_zones_map[warehouse_id]
+ for shipping_zone_id in shipping_zone_ids:
+ quantity_by_shipping_zone_by_product_variant[variant_id][
+ shipping_zone_id
+ ] += quantity
+
quantity_map: DefaultDict[int, int] = defaultdict(int)
for (
variant_id,
diff --git a/saleor/warehouse/models.py b/saleor/warehouse/models.py
index f41390839c..7aba6769da 100644
--- a/saleor/warehouse/models.py
+++ b/saleor/warehouse/models.py
@@ -3,7 +3,7 @@ import uuid
from typing import Set
from django.db import models
-from django.db.models import Exists, F, OuterRef, Sum
+from django.db.models import Exists, F, OuterRef, Q, Sum
from django.db.models.functions import Coalesce
from ..account.models import Address
@@ -62,7 +62,13 @@ class StockQuerySet(models.QuerySet):
def annotate_available_quantity(self):
return self.annotate(
available_quantity=F("quantity")
- - Coalesce(Sum("allocations__quantity_allocated"), 0)
+ - Coalesce(
+ Sum(
+ "allocations__quantity_allocated",
+ filter=Q(allocations__quantity_allocated__gt=0),
+ ),
+ 0,
+ )
)
def for_channel(self, channel_slug: str):