Home > Net >  insert to the table inside loop or bulk insert with django
insert to the table inside loop or bulk insert with django

Time:05-08

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

CodePudding user response:

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.

CodePudding user response:

Pause. I don't exactly know because I dont know everything about your project, but don't you think it would be easier just to make the "orderItem" class just accept item ID or names? Because then it could just use foreign objects and access all those things more easily... And then you just clear the cart after sending it just some sort of item identifier. Not quite sure if this is the answer to your question, however i just thought i would tell you this just incase it helps you.

  • Related