insert to the table inside loop or bulk insert with django

1.1k Views Asked by At

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

1

There are 1 best solutions below

0
On BEST ANSWER

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.