购物车产品数量限制

Limit on Number of cart-products

我想限制可以添加到购物车中的产品数量。

--案例场景:假设交付资源稀缺,我不希望用户一次添加超过5个产品。 (但同一产品的数量可以增加)

cart-app/cart.py

def add(self, product, quantity=1, override_quantity=False):
    product_id = str(product.id)
    if product_id not in self.cart:
        self.cart[product_id] = {'quantity': 0, 'price': str(product.price)}
    if override_quantity:
        self.cart[product_id]['quantity'] = quantity
    else:
        self.cart[product_id]['quantity'] += quantity
    self.save()

def __iter__(self):
    products = Product.objects.filter(id__in=product_ids)
    cart = self.cart.copy()

    for product in products:
        cart[str(product.id)]['product'] = product

    for item in cart.values():
        item['price'] = Decimal(item['price'])
        item['total_price'] = item['price'] * item['quantity']
        yield item

我试过分割我的查询,但这不起作用。有什么想法吗?

product_id 还没有在购物车中,并且购物车已经有五件(或更多)商品时,您可以提出错误:

def add(self, product, quantity=1, override_quantity=False):
    product_id = str(product.id)
    if <b>product_id not in self.cart and len(self.cart) >= 5</b>:
        raise ValueError('Can not add more products to the cart')
    # …

在您看来,您因此可以尝试将商品添加到购物车,如果没有return HTTP 响应:

from django.http import HttpResponse

def my_view(request):
    # …
    try:
        cart.add(product)
    except ValueError:
        return HttpResponse('Can not add to the cart', status=400)
    # …

您需要在添加更多商品之前检查数量。

def add(self, product, quantity=1, override_quantity=False):
    product_id = str(product.id)

    if override_quantity:
        self.cart[product_id]['quantity'] = quantity
    else:
        self.cart[product_id]['quantity'] += quantity
    try:
        if product_id not in self.cart and self.cart[product_id]['quantity'] >= 5:
            self.cart[product_id] = {'quantity': 0, 'price': str(product.price)}
        else:
            print("You can not add more than 5 items.")
    except KeyError:
        print("quantity key is unknown.")
    self.save()