Skip to content

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

Fix high amount of db queries while fetching variant listing (#18404)

Maciej Korycinski533a1a82f6e1
diff --git a/saleor/graphql/product/dataloaders/products.py b/saleor/graphql/product/dataloaders/products.py
index 24e0046a0b..fb7cfae208 100644
--- a/saleor/graphql/product/dataloaders/products.py
+++ b/saleor/graphql/product/dataloaders/products.py
@@ -385,6 +385,29 @@ class VariantChannelListingByVariantIdAndChannelIdLoader(
]
+class VariantChannelListingsByProductIdLoader(
+ DataLoader[int, Iterable[ProductVariantChannelListing]]
+):
+ context_key = "variantchannelistings_by_product_id"
+
+ def batch_load(self, keys: Iterable[int]):
+ variants_channel_listings = (
+ ProductVariantChannelListing.objects.all()
+ .using(self.database_connection_name)
+ .filter(
+ variant__product_id__in=keys,
+ price_amount__isnull=False,
+ )
+ .annotate(product_id=F("variant__product_id"))
+ .order_by("pk")
+ )
+ listing_map = defaultdict(list)
+ for listing in variants_channel_listings.iterator(chunk_size=1000):
+ listing_map[listing.product_id].append(listing)
+
+ return [listing_map[key] for key in keys]
+
+
class VariantsChannelListingByProductIdAndChannelSlugLoader(
DataLoader[ProductIdAndChannelSlug, Iterable[ProductVariantChannelListing]]
):
diff --git a/saleor/graphql/product/tests/benchmark/test_product.py b/saleor/graphql/product/tests/benchmark/test_product.py
index 4a1e6ced6f..4fb269778d 100644
--- a/saleor/graphql/product/tests/benchmark/test_product.py
+++ b/saleor/graphql/product/tests/benchmark/test_product.py
@@ -9,9 +9,10 @@ from .....attribute.tests.model_helpers import (
get_product_attributes,
)
from .....attribute.utils import associate_attribute_values_to_instance
+from .....channel.models import Channel
from .....core.taxes import TaxType
from .....plugins.manager import PluginsManager
-from .....product.models import ProductMedia, ProductTranslation
+from .....product.models import ProductChannelListing, ProductMedia, ProductTranslation
from ....tests.utils import get_graphql_content
@@ -249,11 +250,15 @@ def test_retrieve_product_media(product_list, api_client, count_queries, channel
@pytest.mark.django_db
@pytest.mark.count_queries(autouse=False)
def test_retrieve_channel_listings(
+ django_assert_num_queries,
product_list_with_many_channels,
+ product_list,
staff_api_client,
count_queries,
permission_manage_products,
channel_USD,
+ channel_JPY,
+ channel_PLN,
):
query = """
query($channel: String) {
@@ -313,15 +318,49 @@ def test_retrieve_channel_listings(
}
"""
+ assert Channel.objects.count() > 1
+
variables = {"channel": channel_USD.slug}
- get_graphql_content(
- staff_api_client.post_graphql(
- query,
- variables,
- permissions=(permission_manage_products,),
- check_no_permissions=False,
+
+ expected_db_queries = 14
+ with django_assert_num_queries(expected_db_queries):
+ get_graphql_content(
+ staff_api_client.post_graphql(
+ query,
+ variables,
+ permissions=(permission_manage_products,),
+ check_no_permissions=False,
+ )
)
+
+ ProductChannelListing.objects.bulk_create(
+ [
+ ProductChannelListing(
+ product=product_list[0],
+ channel=channel_JPY,
+ is_published=True,
+ ),
+ ProductChannelListing(
+ product=product_list[1],
+ channel=channel_JPY,
+ is_published=True,
+ ),
+ ProductChannelListing(
+ product=product_list[2],
+ channel=channel_JPY,
+ is_published=True,
+ ),
+ ]
)
+ with django_assert_num_queries(expected_db_queries):
+ get_graphql_content(
+ staff_api_client.post_graphql(
+ query,
+ variables,
+ permissions=(permission_manage_products,),
+ check_no_permissions=False,
+ )
+ )
@pytest.mark.django_db
diff --git a/saleor/graphql/product/types/channels.py b/saleor/graphql/product/types/channels.py
index 4e622c38e1..2a6e1261bf 100644
--- a/saleor/graphql/product/types/channels.py
+++ b/saleor/graphql/product/types/channels.py
@@ -34,11 +34,7 @@ from ...tax.dataloaders import (
TaxConfigurationByChannelId,
TaxConfigurationPerCountryByTaxConfigurationIDLoader,
)
-from ..dataloaders import (
- ProductVariantsByProductIdLoader,
- VariantChannelListingByVariantIdAndChannelSlugLoader,
- VariantsChannelListingByProductIdAndChannelSlugLoader,
-)
+from ..dataloaders.products import VariantChannelListingsByProductIdLoader
class Margin(BaseObjectType):
@@ -135,79 +131,57 @@ class ProductChannelListing(ModelObjectType[models.ProductChannelListing]):
@staticmethod
@traced_resolver
def resolve_purchase_cost(root: models.ProductChannelListing, info):
- channel = ChannelByIdLoader(info.context).load(root.channel_id)
-
- def calculate_margin_with_variants(variants):
- def calculate_margin_with_channel(channel):
- def calculate_margin_with_channel_listings(
- variant_channel_listings: list[
- models.ProductVariantChannelListing | None
- ],
- ):
- existing_listings = list(filter(None, variant_channel_listings))
- if not existing_listings:
- return None
-
- has_variants = True if len(variant_ids_channel_slug) > 0 else False
- purchase_cost, _margin = get_product_costs_data(
- existing_listings, has_variants, root.currency
- )
- return purchase_cost
-
- variant_ids_channel_slug = [
- (variant.id, channel.slug) for variant in variants
- ]
- return (
- VariantChannelListingByVariantIdAndChannelSlugLoader(info.context)
- .load_many(variant_ids_channel_slug)
- .then(calculate_margin_with_channel_listings)
- )
-
- return channel.then(calculate_margin_with_channel)
+ def calculate_margin_with_channel_listings(
+ variant_channel_listings: list[models.ProductVariantChannelListing | None],
+ ):
+ existing_listings: list[models.ProductVariantChannelListing] = []
+ for listing in variant_channel_listings:
+ if not listing:
+ continue
+ if listing.channel_id == root.channel_id:
+ existing_listings.append(listing)
+
+ if not existing_listings:
+ return None
+
+ has_variants = True
+ purchase_cost, _margin = get_product_costs_data(
+ existing_listings, has_variants, root.currency
+ )
+ return purchase_cost
return (
- ProductVariantsByProductIdLoader(info.context)
+ VariantChannelListingsByProductIdLoader(info.context)
.load(root.product_id)
- .then(calculate_margin_with_variants)
+ .then(calculate_margin_with_channel_listings)
)
@staticmethod
@traced_resolver
def resolve_margin(root: models.ProductChannelListing, info):
- channel = ChannelByIdLoader(info.context).load(root.channel_id)
-
- def calculate_margin_with_variants(variants):
- def calculate_margin_with_channel(channel):
- def calculate_margin_with_channel_listings(
- variant_channel_listings: list[
- models.ProductVariantChannelListing | None
- ],
- ):
- existing_listings = list(filter(None, variant_channel_listings))
- if not existing_listings:
- return None
-
- has_variants = True if len(variant_ids_channel_slug) > 0 else False
- _purchase_cost, margin = get_product_costs_data(
- existing_listings, has_variants, root.currency
- )
- return Margin(margin[0], margin[1])
-
- variant_ids_channel_slug = [
- (variant.id, channel.slug) for variant in variants
- ]
- return (
- VariantChannelListingByVariantIdAndChannelSlugLoader(info.context)
- .load_many(variant_ids_channel_slug)
- .then(calculate_margin_with_channel_listings)
- )
-
- return channel.then(calculate_margin_with_channel)
+ def calculate_margin_with_channel_listings(
+ variant_channel_listings: list[models.ProductVariantChannelListing | None],
+ ):
+ existing_listings: list[models.ProductVariantChannelListing] = []
+ for listing in variant_channel_listings:
+ if not listing:
+ continue
+ if listing.channel_id == root.channel_id:
+ existing_listings.append(listing)
+
+ if not existing_listings:
+ return None
+
+ has_variants = True
+ _purchase_cost, margin = get_product_costs_data(
+ existing_listings, has_variants, root.currency
+ )
+ return Margin(margin[0], margin[1])
return (
- ProductVariantsByProductIdLoader(info.context)
+ VariantChannelListingsByProductIdLoader(info.context)
.load(root.product_id)
- .then(calculate_margin_with_variants)
+ .then(calculate_margin_with_channel_listings)
)
@staticmethod
@@ -229,7 +203,16 @@ class ProductChannelListing(ModelObjectType[models.ProductChannelListing]):
def load_variant_channel_listings(data):
tax_configs_per_country = data
- def load_default_tax_rate(variants_channel_listing):
+ def load_default_tax_rate(
+ variants_channel_listings: list[
+ models.ProductVariantChannelListing
+ ],
+ ):
+ variants_channel_listing = []
+ for listing in variants_channel_listings:
+ if listing and listing.channel_id == channel.id:
+ variants_channel_listing.append(listing)
+
if not variants_channel_listing:
return None
@@ -289,8 +272,8 @@ class ProductChannelListing(ModelObjectType[models.ProductChannelListing]):
)
return (
- VariantsChannelListingByProductIdAndChannelSlugLoader(context)
- .load((root.product_id, channel.slug))
+ VariantChannelListingsByProductIdLoader(context)
+ .load(root.product_id)
.then(load_default_tax_rate)
)