我想限制可以添加到购物车的产品数量。
--案例场景:假设交付资源稀缺,我不希望用户一次添加超过 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
我试过对查询进行切片,但这不起作用。有什么想法吗?
答案 0 :(得分:1)
当 product_id
尚未在购物车中并且购物车已有五件(或更多)商品时,您可以引发错误:
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')
# …
在您的视图中,您可以尝试将商品添加到购物车,如果没有,则返回 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)
# …
答案 1 :(得分:0)
您需要在添加更多商品之前检查数量。
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()