Home > Net >  How can i update quantity in the django cart?
How can i update quantity in the django cart?

Time:07-28

model.py


class OrderItem(models.Model):
    product = models.ForeignKey(Product,on_delete=models.CASCADE)
    order = models.ForeignKey(Order, on_delete=models.CASCADE)
    quantity = models.IntegerField()
    date_added = models.DateTimeField(auto_now_add=True)
    if request.method == "POST":
        customer = request.user.customer
        order ,created = Order.objects.get_or_create(customer=customer,complete=False)
        id = request.POST.get('id')
        product = Product.objects.get(id=id)
        if OrderItem.objects.filter(product=product):
                orderitem = OrderItem.objects.filter(product=product)
                orderitem.quantity =1
                order.save()

            
        else:
            orderitem = OrderItem.objects.create(product=product,order=order,quantity=1)
    products = Product.objects.all()
    return render(request, "HTML/index.html",{'products':products})

Error

QuerySet' object has no attribute 'quantity'

I'm trying to a cart if an item exists in this cart, the system should update its quantity, if not then a new item should be created in the cart, how can i do that?

CodePudding user response:

You are trying to update the quantity field to a queryset and not to an object. If you need to get a object use ".get" instead of ".filter" like this:

    if OrderItem.objects.filter(product=product).exists():
                orderitem = OrderItem.objects.get(product=product)
                orderitem.quantity =1
                orderitem.save()
                order.save()

CodePudding user response:

Basically the @STACCAH_STACCAH answer is not fully correct, you can have multiple OrderItem instances attached to the product. So you should do this that way:

order_items = OrderItem.objects.filter(product=product)
for item in order_items:
    item.quantity  = 1
    item.save()

It's should be enough, you don't need to check if the object exist at all because QuerySet is iterable even when amount of elements is certainly zero. Basically that means forloop will not raise exception while iterating on OrderItem instances.

  • Related