Item does not decrease Django

Viewed 29

Hello I want to make a feature, that if I click quantity decrease by 1 but it does not decrease and only returns HttpResponse.

class CartView(TemplateView):
    template_name = "shop/cart.html"
    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['cart'] = Cart.objects.annotate(
        price=Sum(F('orderitem__item__price') * F('orderitem__quantity'))
        ).get(order_user= self.request.user)
        cart = context['cart']
        cart.total = cart.price
        cart.save()
        context['order_items'] = OrderItem.objects.filter(cart=cart)
        return context
    def post(self, request):
        if 'minus' in request.POST:
            cart = Cart.objects.get(order_user=self.request.user)
            primary = request.POST.get('orderitem__id')
            item = OrderItem.objects.filter(id=primary, cart=cart)
            item.quantity = F('quantity') - 1
            item.update()
            return HttpResponse("cart uptaded")
1 Answers

Item is a QuerySet, you do not update a queryset by altering an attribute: you use the parameters in the .update(…) method [Django-doc] for that:

OrderItem.objects.filter(id=primary, cart=cart).update(
    quantity=F('quantity')-1
)
Related