MultipleObjectsReturned at /add-to-cart/ get()返回了多个Cart --它返回了2个!
@login_required
def add_to_cart(request):
user = request.user
product_id = request.GET.get('prod_id')
if Cart.objects.filter(product=product_id).exists():
prod_id = request.GET['prod_id']
try:
product = Cart.objects.get(product=prod_id)
except Cart.DoesNotExist:
product = None
c = Cart.objects.get(Q(product=prod_id) & Q(user=request.user))
c.quantity += 1
c.save()
user = request.user
cart = Cart.objects.filter(user=user)
amount = 0
for p in cart:
value = p.quantity * p.product.discounted_price
amount = amount + value
totalamount = amount + 300
print(prod_id)
data = {
'quantity': c.quantity,
'amount': amount,
'totalamount': totalamount
}
return redirect('/cart')
else:
pass
product = Product.objects.get(id=product_id)
Cart(user=user, product=product).save()
return redirect('/cart')
我试过了,请帮帮我。如果产品在另一个购物篮中,则不希望将其添加到用户。
1条答案
按热度按时间yzuktlbb1#
Cart.objects.get(product__id = product_id)