'decreasing values with loop in Django

in this code, I tried to decrease the quantity of products from the database when the user places the order, it is working but the problem is just decreasing from the first product in the cart?

  new_order_items = Cart.objects.filter(user=request.user)
        for item in new_order_items:
            OrderItem.objects.create(
                order=neworder,
                product=item.product,
                price=item.product.selling_price,
                quantity=item.product_quantity
            )
            # decrease the product quantity from table
            order_product = Product.objects.filter(id=item.product_id).first()
            order_product.quantity = order_product.quantity - item.product_quantity
            order_product.save()


Solution 1:[1]

i'm suggesting to not use a loop for the filtered item that will cause a performance issue, instead you could use bulk_create() and instead of looping for each item you can use .values() method

products_id=Cart.objects.filter(user=request.user).values('product_id')
#that will return a query set of item ids

then you can search by query using field__in= for example :

order_product = Product.objects.filter(id__in=item.products_id)
#that will return a query set of products with that id

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ali fareeq