Reputation: 881
an item does not delete when it its quantity is 0 and it keeps getting negative numbers. What did I wrong, how can I solve the problem.
def post(self, request, pk):
if 'minus' in request.POST:
cart = Cart.objects.get(order_user=self.request.user)
item = OrderItem.objects.get(id=pk, cart=cart)
item.quantity=F('quantity')-1
if item.quantity == 0:
item.delete()
else:
item.save()
print(item.quantity)
Upvotes: 1
Views: 98
Reputation: 477210
If you set item.quantity = F('quantity')-1
then this is not equal to 0
: it is an expression F('quantity')-1
.
You can check if the item is less than or equal to 1
and remove it, otherwise you can decrement it. For example with:
def post(self, request, pk):
if 'minus' in request.POST:
cart = Cart.objects.get(order_user=self.request.user)
qs = OrderItem.objects.filter(id=pk, cart=cart, quantity__lte=1)
if not qs.delete()[0]:
OrderItem.objects.filter(
id=pk, cart=cart
).update(quantity=F('quantity')-1)
# …
# …
Upvotes: 1