Skip to content
Advertisement

In my List of multiple dictionaries only my last dictionary item save on database, I want to save all [closed]

I would like to save each dictionary as a separate instance of a db model using sqlalchemy.

I tried

 from models.ordermodels import OrderModel, OrderItemsModel

    for dic in request.cartItems:
        order_item_a = OrderItemsModel(
                    name=dic.name,
                    quantity=dic.quantity,
                    price=dic.price,
                    order_id=x,
         )
    
                    db.add(order_item_a)

in output

"cartItems": [
    {
      "name": "string",
      "quantity": 0,
      "price": 0
    },
    {
      "name": "string",
      "quantity": 110,
      "price": 0
    }
  ]

It only saves the last item , I want to save all the item in database. I’m using Postgresql

Advertisement

Answer

I’m pretty sure that only the last item is saved because you only save the last item.

You probably wrote something like this:

from models.ordermodels import OrderModel, OrderItemsModel

for dic in request.cartItems:
    order_item_a = OrderItemsModel(
        name=dic.name,
        quantity=dic.quantity,
        price=dic.price,
        order_id=x,
    )

db.add(order_item_a)

when in fact you should have written this:

from models.ordermodels import OrderModel, OrderItemsModel

for dic in request.cartItems:
    order_item_a = OrderItemsModel(
        name=dic.name,
        quantity=dic.quantity,
        price=dic.price,
        order_id=x,
    )

    db.add(order_item_a)
Advertisement