Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Prefetch more data with cart, to avoid multiple SQL queries
Artur Smętc99f91db1db9
diff --git a/saleor/cart/decorators.py b/saleor/cart/decorators.pyindex 8cae7e3c9d..3113b4e3dd 100644--- a/saleor/cart/decorators.py+++ b/saleor/cart/decorators.py@@ -21,10 +21,9 @@ def find_and_assign_cart(request, response):response.delete_cookie(Cart.COOKIE_NAME)-def get_cart_from_request(request, create=False):+def get_cart_from_request(request, create=False, prefetch_product_data=False):"""Returns Cart object for current user. If create option is True,new cart will be saved to db"""-cookie_token = request.get_signed_cookie(Cart.COOKIE_NAME, default=None)@@ -36,7 +35,8 @@ def get_cart_from_request(request, create=False):user = Nonequeryset = Cart.objects.anonymous()token = cookie_token-+ if prefetch_product_data:+ queryset = queryset.with_products_data()try:cart = queryset.open().get(token=token)except Cart.DoesNotExist:@@ -72,6 +72,16 @@ def get_or_empty_db_cart(view):return func+def get_or_empty_db_cart_with_product_data(view):+ """Get user cart if exists"""+ @wraps(view)+ def func(request, *args, **kwargs):+ cart = get_cart_from_request(+ request, prefetch_product_data=True)+ return view(request, cart, *args, **kwargs)+ return func++def assign_anonymous_cart(view):"""After login anonymous session cart will be assigned to user"""@wraps(view)diff --git a/saleor/cart/models.py b/saleor/cart/models.pyindex e1c3ad3b7b..1a97c909ac 100644--- a/saleor/cart/models.py+++ b/saleor/cart/models.py@@ -52,6 +52,12 @@ class CartQueryset(models.QuerySet):def save(self):self.update(status=Cart.SAVED)+ def with_products_data(self):+ return self.prefetch_related(+ 'lines', 'lines__variant', 'lines__variant__product__attributes',+ 'lines__variant__stock', 'lines__variant__product__images',+ 'lines__variant__product')+class Cart(models.Model):@@ -214,7 +220,6 @@ class CartLine(models.Model, ItemLine):validators=[MinValueValidator(0), MaxValueValidator(999)])data = JSONField(blank=True, default={})-class Meta:unique_together = ('cart', 'variant', 'data')diff --git a/saleor/cart/views.py b/saleor/cart/views.pyindex d071dda176..6f446e803a 100644--- a/saleor/cart/views.py+++ b/saleor/cart/views.py@@ -11,19 +11,18 @@ from django.template.response import TemplateResponsefrom ..core.utils import to_local_currencyfrom ..product.forms import get_form_class_for_productfrom ..product.models import Product, ProductVariant-from .decorators import get_or_create_db_cart, get_or_empty_db_cart+from . import decoratorsfrom .forms import ReplaceCartLineFormfrom .utils import check_product_availability_and_warn-@get_or_empty_db_cart[email protected]_or_empty_db_cart_witch_product_datadef index(request, cart):- cart_lines = cart.lines.select_related('variant')- check_product_availability_and_warn(request, cart_lines)discounts = request.discountscart_lines = []+ check_product_availability_and_warn(request, cart)- for line in cart:+ for line in cart.lines.all():initial = {'quantity': line.get_quantity()}form = ReplaceCartLineForm(None, cart=cart, variant=line.variant,initial=initial, discounts=discounts)@@ -47,7 +46,7 @@ def index(request, cart):'local_cart_total': local_cart_total})-@get_or_create_db_cart[email protected]_or_create_db_cartdef add_to_cart(request, cart, product_id):product = get_object_or_404(Product, pk=product_id)form_class = get_form_class_for_product(product)@@ -64,7 +63,7 @@ def add_to_cart(request, cart, product_id):return redirect('cart:index')-@get_or_empty_db_cart[email protected]_or_empty_db_cartdef update(request, cart, variant_id):if not request.is_ajax():return redirect('cart:index')diff --git a/saleor/checkout/core.py b/saleor/checkout/core.pyindex 7dbaf71236..e89af235ae 100644--- a/saleor/checkout/core.py+++ b/saleor/checkout/core.py@@ -7,7 +7,7 @@ from django.forms.models import model_to_dictfrom django.utils.encoding import smart_textfrom prices import Price, FixedDiscount-from ..cart.views import get_or_empty_db_cart+from ..cart.decorators import get_or_empty_db_cartfrom ..core import analyticsfrom ..discount.models import Voucher, NotApplicablefrom ..order.models import Orderdiff --git a/tests/conftest.py b/tests/conftest.pyindex 980196ba65..35f6fea1dc 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -27,9 +27,10 @@ def customer_user(db): # pylint: disable=W0613@pytest.fixturedef request_cart(cart, monkeypatch):+ # FIXME: Fixtures should not have any side effectsmonkeypatch.setattr(decorators, 'get_cart_from_request',- lambda request, create=False: cart)+ lambda request, create=False, prefetch_product_data=False: cart)return cartdiff --git a/tests/test_order.py b/tests/test_order.pyindex fcc3f1c103..535a215b26 100644--- a/tests/test_order.py+++ b/tests/test_order.py@@ -32,7 +32,7 @@ def test_stock_allocation(billing_address, product_in_stock):cart.add(variant, quantity=2)order = models.Order.objects.create(billing_address=billing_address)delivery_group = models.DeliveryGroup.objects.create(order=order)- delivery_group.add_items_from_partition(cart)+ delivery_group.add_items_from_partition(cart.lines.all())order_line = delivery_group.items.get()stock = order_line.stockassert stock.quantity_allocated == 2@@ -41,7 +41,7 @@ def test_stock_allocation(billing_address, product_in_stock):def test_dashboard_change_quantity_form(request_cart_with_item, order):cart = request_cart_with_itemgroup = models.DeliveryGroup.objects.create(order=order)- group.add_items_from_partition(cart)+ group.add_items_from_partition(cart.lines.all())order_line = group.items.get()# Check available quantity validation