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

Question:

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

Asked By: Soumick Barua

||

Answers:

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)
Answered By: Vsevolod Timchenko
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.