djangolimitcartobject-slicing

Limit on Number of cart-products


I'd like to set a limit on the number of products that can be added on a cart.

--Case scenario: Assuming delivery-resource scarcity, I don't want users to add more than 5 products at a time. (The quantity of same product can, however, be raised)

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

I've tried slicing my queries but this doesn't work. Any ideas?


Solution

  • You can raise an error when the product_id is not yet in the cart, and the cart already has five (or more) items:

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

    In your views, you thus can try to add the item to the cart, and if not return a HTTP response:

    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)
        # …