Skip to content

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

Refactor line weight calculation to reuse DB queries (#15714)

Marcin Gębala16ba23e9b248
diff --git a/saleor/checkout/complete_checkout.py b/saleor/checkout/complete_checkout.py
index a974813af6..4aaad9f206 100644
--- a/saleor/checkout/complete_checkout.py
+++ b/saleor/checkout/complete_checkout.py
@@ -82,6 +82,7 @@ from .fetch import (
)
from .models import Checkout
from .utils import (
+ calculate_checkout_weight,
get_checkout_metadata,
get_or_create_checkout_metadata,
get_voucher_for_checkout_info,
@@ -155,7 +156,7 @@ def _process_shipping_data_for_order(
"shipping_address": shipping_address,
"base_shipping_price": base_shipping_price,
"shipping_price": shipping_price,
- "weight": checkout_info.checkout.get_total_weight(lines),
+ "weight": calculate_checkout_weight(lines),
**get_shipping_tax_class_kwargs_for_order(tax_class),
}
result.update(delivery_method_info.delivery_method_order_field)
diff --git a/saleor/checkout/fetch.py b/saleor/checkout/fetch.py
index 4965f0c7ba..c4861ea433 100644
--- a/saleor/checkout/fetch.py
+++ b/saleor/checkout/fetch.py
@@ -671,7 +671,7 @@ def update_delivery_method_lists_for_checkout_info(
)
# Filter shipping methods using sync webhooks
excluded_methods = manager.excluded_shipping_methods_for_checkout(
- checkout_info.checkout, all_methods
+ checkout_info.checkout, checkout_info.channel, all_methods
)
initialize_shipping_method_active_status(all_methods, excluded_methods)
return all_methods
diff --git a/saleor/checkout/models.py b/saleor/checkout/models.py
index 04011e966e..8f4ae38288 100644
--- a/saleor/checkout/models.py
+++ b/saleor/checkout/models.py
@@ -1,10 +1,9 @@
"""Checkout-related ORM models."""
-from collections.abc import Iterable
from datetime import date
from decimal import Decimal
from operator import attrgetter
-from typing import TYPE_CHECKING, Optional, Union
+from typing import TYPE_CHECKING, Optional
from uuid import uuid4
from django.conf import settings
@@ -19,19 +18,14 @@ from prices import Money
from ..channel.models import Channel
from ..core.models import ModelWithMetadata
from ..core.taxes import zero_money
-from ..core.weight import zero_weight
from ..giftcard.models import GiftCard
from ..permission.enums import CheckoutPermissions
from ..shipping.models import ShippingMethod
from . import CheckoutAuthorizeStatus, CheckoutChargeStatus
if TYPE_CHECKING:
- from django_measurement import Weight
-
- from ..order.fetch import OrderLineInfo
from ..payment.models import Payment
from ..product.models import ProductVariant
- from .fetch import CheckoutLineInfo
def get_default_country():
@@ -234,19 +228,6 @@ class Checkout(models.Model):
return zero_money(currency=self.currency)
return Money(balance, self.currency)
- def get_total_weight(
- self, lines: Union[Iterable["CheckoutLineInfo"], Iterable["OrderLineInfo"]]
- ) -> "Weight":
- # FIXME: it does not make sense for this method to live in the Checkout model
- # since it's used in the Order model as well. We should move it to a separate
- # helper.
- weights = zero_weight()
- for checkout_line_info in lines:
- line = checkout_line_info.line
- if line.variant:
- weights += line.variant.get_weight() * line.quantity
- return weights
-
def get_line(self, variant: "ProductVariant") -> Optional["CheckoutLine"]:
"""Return a line matching the given variant and data if any."""
matching_lines = (line for line in self if line.variant.pk == variant.pk)
diff --git a/saleor/checkout/tests/test_cart.py b/saleor/checkout/tests/test_cart.py
index 48747849ff..55011b6f7a 100644
--- a/saleor/checkout/tests/test_cart.py
+++ b/saleor/checkout/tests/test_cart.py
@@ -10,7 +10,11 @@ from ...plugins.manager import get_plugins_manager
from ...product.models import Category
from .. import calculations, utils
from ..models import Checkout
-from ..utils import add_variant_to_checkout, calculate_checkout_quantity
+from ..utils import (
+ add_variant_to_checkout,
+ calculate_checkout_quantity,
+ calculate_checkout_weight,
+)
@pytest.fixture
@@ -283,4 +287,4 @@ def test_get_total_weight(checkout_with_item):
line.quantity = 6
line.save()
lines, _ = fetch_checkout_lines(checkout_with_item)
- assert checkout_with_item.get_total_weight(lines) == Weight(kg=60)
+ assert calculate_checkout_weight(lines) == Weight(kg=60)
diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.py
index 9d8f97082c..4aa267258d 100644
--- a/saleor/checkout/utils.py
+++ b/saleor/checkout/utils.py
@@ -22,6 +22,7 @@ from ..core.utils.promo_code import (
promo_code_is_voucher,
)
from ..core.utils.translations import get_translation
+from ..core.weight import zero_weight
from ..discount import DiscountType, VoucherType
from ..discount.interface import VoucherInfo, fetch_voucher_info
from ..discount.models import (
@@ -59,6 +60,8 @@ from .fetch import (
from .models import Checkout, CheckoutLine, CheckoutMetadata
if TYPE_CHECKING:
+ from measurement.measures import Weight
+
from ..account.models import Address
from ..order.models import Order
from .fetch import CheckoutInfo, CheckoutLineInfo
@@ -865,6 +868,7 @@ def get_valid_internal_shipping_methods_for_checkout(
checkout_info.checkout,
channel_id=checkout_info.checkout.channel_id,
price=subtotal,
+ shipping_address=checkout_info.shipping_address,
country_code=country_code,
lines=lines,
)
@@ -1024,3 +1028,21 @@ def get_checkout_metadata(checkout: "Checkout"):
return checkout.metadata_storage
else:
return CheckoutMetadata(checkout=checkout)
+
+
+def calculate_checkout_weight(lines: Iterable["CheckoutLineInfo"]) -> "Weight":
+ weights = zero_weight()
+ for checkout_line_info in lines:
+ variant = checkout_line_info.variant
+ if variant:
+ line_weight = get_checkout_line_weight(checkout_line_info)
+ weights += line_weight * checkout_line_info.line.quantity
+ return weights
+
+
+def get_checkout_line_weight(line_info: "CheckoutLineInfo"):
+ return (
+ line_info.variant.weight
+ or line_info.product.weight
+ or line_info.product_type.weight
+ )
diff --git a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py
index d112bbcf12..802fbe36d7 100644
--- a/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py
+++ b/saleor/graphql/checkout/tests/benchmark/test_checkout_mutations.py
@@ -562,7 +562,7 @@ def test_create_checkout_with_order_promotion(
}
# when
- with django_assert_num_queries(88):
+ with django_assert_num_queries(71):
response = user_api_client.post_graphql(MUTATION_CHECKOUT_CREATE, variables)
# then
diff --git a/saleor/graphql/order/tests/queries/test_order.py b/saleor/graphql/order/tests/queries/test_order.py
index 3b25d60607..20e2890993 100644
--- a/saleor/graphql/order/tests/queries/test_order.py
+++ b/saleor/graphql/order/tests/queries/test_order.py
@@ -349,7 +349,7 @@ def test_order_query(
expected_methods = ShippingMethod.objects.applicable_shipping_methods(
price=order.subtotal.gross,
- weight=order.get_total_weight(),
+ weight=order.weight,
country_code=order.shipping_address.country.code,
channel_id=order.channel_id,
)
@@ -997,7 +997,7 @@ def test_order_query_in_pln_channel(
expected_methods = ShippingMethod.objects.applicable_shipping_methods(
price=order.subtotal.gross,
- weight=order.get_total_weight(),
+ weight=order.weight,
country_code=order.shipping_address.country.code,
channel_id=order.channel_id,
)
diff --git a/saleor/order/models.py b/saleor/order/models.py
index 79ce62b9a0..469dc01659 100644
--- a/saleor/order/models.py
+++ b/saleor/order/models.py
@@ -498,9 +498,6 @@ class Order(ModelWithMetadata, ModelWithExternalReference):
def total_balance(self):
return self.total_charged - self.total.gross
- def get_total_weight(self, _lines=None):
- return self.weight
-
class OrderLineQueryset(models.QuerySet["OrderLine"]):
def digital(self):
diff --git a/saleor/order/tests/test_order.py b/saleor/order/tests/test_order.py
index 89c6ad9f3d..7cc2c18b78 100644
--- a/saleor/order/tests/test_order.py
+++ b/saleor/order/tests/test_order.py
@@ -658,12 +658,12 @@ def test_get_order_weight_non_existing_product(
app=None,
manager=anonymous_plugins,
)
- old_weight = order.get_total_weight()
+ old_weight = order.weight
product.delete()
order.refresh_from_db()
- new_weight = order.get_total_weight()
+ new_weight = order.weight
assert old_weight == new_weight
diff --git a/saleor/order/utils.py b/saleor/order/utils.py
index ed0317155c..fcbe3e1503 100644
--- a/saleor/order/utils.py
+++ b/saleor/order/utils.py
@@ -611,7 +611,8 @@ def get_all_shipping_methods_for_order(
if not order.is_shipping_required():
return []
- if not order.shipping_address:
+ shipping_address = order.shipping_address
+ if not shipping_address:
return []
all_methods = []
@@ -622,7 +623,8 @@ def get_all_shipping_methods_for_order(
order,
channel_id=order.channel_id,
price=order.subtotal.gross,
- country_code=order.shipping_address.country.code,
+ shipping_address=shipping_address,
+ country_code=shipping_address.country.code,
)
.prefetch_related("channel_listings")
)
diff --git a/saleor/plugins/manager.py b/saleor/plugins/manager.py
index ae05b8c464..9ae90c1e61 100644
--- a/saleor/plugins/manager.py
+++ b/saleor/plugins/manager.py
@@ -2164,6 +2164,7 @@ class PluginsManager(PaymentInterface):
def excluded_shipping_methods_for_checkout(
self,
checkout: "Checkout",
+ channel: "Channel",
available_shipping_methods: list["ShippingMethodData"],
) -> list[ExcludedShippingMethod]:
return self.__run_method_on_plugins(
@@ -2171,7 +2172,7 @@ class PluginsManager(PaymentInterface):
[],
checkout,
available_shipping_methods,
- channel_slug=checkout.channel.slug,
+ channel_slug=channel.slug,
)
def perform_mutation(
diff --git a/saleor/shipping/models.py b/saleor/shipping/models.py
index 996aed4275..bebcdc01cc 100644
--- a/saleor/shipping/models.py
+++ b/saleor/shipping/models.py
@@ -24,6 +24,7 @@ from . import PostalCodeRuleInclusionType, ShippingMethodType
from .postal_codes import filter_shipping_methods_by_postal_code_rules
if TYPE_CHECKING:
+ from ..account.models import Address
from ..checkout.fetch import CheckoutLineInfo
from ..checkout.models import Checkout
from ..order.fetch import OrderLineInfo
@@ -165,32 +166,44 @@ class ShippingMethodQueryset(models.QuerySet["ShippingMethod"]):
instance: Union["Checkout", "Order"],
channel_id,
price: Money,
+ shipping_address: Optional["Address"] = None,
country_code: Optional[str] = None,
lines: Union[
Iterable["CheckoutLineInfo"], Iterable["OrderLineInfo"], None
] = None,
):
- if not instance.shipping_address:
+ if not shipping_address:
return None
+
if not country_code:
- # TODO: country_code should come from argument
- country_code = instance.shipping_address.country.code
+ country_code = shipping_address.country.code
+
if lines is None:
# TODO: lines should comes from args in get_valid_shipping_methods_for_order
lines = list(instance.lines.prefetch_related("variant__product").all()) # type: ignore[misc] # this is hack # noqa: E501
instance_product_ids = {
line.variant.product_id for line in lines if line.variant
}
+
+ from ..checkout.models import Checkout
+
+ if isinstance(instance, Checkout):
+ from ..checkout.utils import calculate_checkout_weight
+
+ weight = calculate_checkout_weight(lines) # type: ignore[arg-type]
+ else:
+ weight = instance.weight
+
applicable_methods = self.applicable_shipping_methods(
price=price,
channel_id=channel_id,
- weight=instance.get_total_weight(lines),
- country_code=country_code or instance.shipping_address.country.code,
+ weight=weight,
+ country_code=country_code,
product_ids=instance_product_ids,
).prefetch_related("postal_code_rules")
return filter_shipping_methods_by_postal_code_rules(
- applicable_methods, instance.shipping_address
+ applicable_methods, shipping_address
)