21bn
21bn

Reputation: 147

Flask Sqlalchemy add multiple row

I am using flask-restful this is My class I want to insert

class OrderHistoryResource(Resource):

    model = OrderHistoryModel
    schema = OrderHistorySchema
    order = OrderModel
    product = ProductModel

    def post(self):
        value = req.get_json()
        data = cls.schema(many=True).load(value)  
        data.insert()

In my model

def insert(self):
    db.session.add(self)
    db.session.commit()

schema

from config.ma import ma
from model.orderhistory import OrderHistoryModel

class OrderHistorySchema(ma.ModelSchema):
    class Meta:
        model = OrderHistoryModel
        include_fk = True

Example Data I want to insert

[
    {
        "quantity":99,
        "flaskSaleStatus":true,
        "orderId":"ORDER_64a79028d1704406b6bb83b84ad8c02a_1568776516",
        "proId":"PROD_9_1568779885_64a79028d1704406b6bb83b84ad8c02a"
     },
     {
        "quantity":89,
        "flaskSaleStatus":true,
        "orderId":"ORDER_64a79028d1704406b6bb83b84ad8c02a_1568776516",
        "proId":"PROD_9_1568779885_64a79028d1704406b6bb83b84ad8c02a"
     }
]

this is what i got after insert method has started

TypeError: insert() takes exactly 2 arguments (0 given)

or there is another way to do this action?

Upvotes: 4

Views: 14135

Answers (2)

elembie
elembie

Reputation: 640

Edited - released marshmallow-sqlalchemy loads directly to instance

You need to loop through the OrderModel instances in your list.

You can then use add_all to add the OrderModel objects to the session, then bulk update - see the docs

Should be something like:

db.session.add_all(data)
db.session.commit() 

See this post for brief discussion on why add_all is best when you have complex ORM relationships.

Also - not sure you need to have all your models/schemas as class variables, it's fine to have them imported (or just present in the same file, as long as they're declared before the resource class).

Upvotes: 11

stasiekz
stasiekz

Reputation: 1853

You are calling insert on list cause data is list of model OrderHistoryModel instances.

Also post method doesn't need to be classmethod and you probably had an error there as well.

Since data is list of model instances you can use db.session.add_all method to add them to session in bulk.

    def post(self):
        value = req.get_json()
        data = self.schema(many=True).load(value)
        db.session.add_all(data)
        db.session.commit() 

Upvotes: 0

Related Questions