0

i need to insert all products in the Cart table to the table called (OrderItem), I have used this code:

 neworder.save()

        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()

this code above only inserted the first product from the cart inside the Item_orders table? Although I have used the loop?

Thanks

Osama Mohammed
  • 2,433
  • 13
  • 29
  • 61
  • Do you return something in the loop? Or does it raise an error? – Willem Van Onsem May 07 '22 at 13:06
  • no errors, just insert the first order in the cart without any problem, like there is no loop – Osama Mohammed May 07 '22 at 13:08
  • @OsamaMohammed So what you want now, can you please clarify, and `filter(id=item.product_id).first()` doesn't seem right to me as item is a temporary variable of a loop to add records as your current code says, so how can you filter through it? – Sunderam Dubey May 07 '22 at 13:13
  • my problem with inserting into the OrderItem table, although it is inside the loop, only the first product inserted not all products from the cart – Osama Mohammed May 07 '22 at 13:16

1 Answers1

1

Can you try with this approach

from django.db import transaction
from django.db.models import F
with transaction.atomic():
    new_order_items = Cart.objects.filter(user=request.user)
    print(new_order_items) # check if we are getting more than 1 value or not it may be the reason that your loop run one time only bcz of this
    orders = []
    for item in new_order_items:
        orders.append(OrderItem(
            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).update(quantity=F('quantity')-item.product_quantity) #Product id should be unique so this line should be
    OrderItem.objects.bulk_create(orders)

Also you should keep these types of updates in atomic transactions else if someone updates the product quantity while you are creating objects then it will create a mess on live.

Deepak Tripathi
  • 3,175
  • 1
  • 8
  • 21