插入到 table 内部循环或使用 django 批量插入

insert to the table inside loop or bulk insert with django

我需要将购物车 table 中的所有产品插入名为 (OrderItem) 的 table,我使用了此代码:

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

上面的代码仅将购物车中的第一个产品插入 Item_orders table?虽然我用过loop?

谢谢

你能试试这个方法吗

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)

此外,您应该在原子事务中保留这些类型的更新,否则如果有人在您创建对象时更新了产品数量,那么它会在现场造成混乱。