ka ern
ka ern

Reputation: 337

How to insert multiple records using JSON in SQLAlchemy

I want to insert multiple records using json like this:

posts = [{
            "title": "First Post",
            "user_id": 1
        }, 
        {
            "title": "Second Post", 
            "user_id": 2
        }]

How do you save posts like this way?:

post = Post(title=posts.title, user_id=posts.user_id)
db.session.add(post)
db.session.commit()

I am using flask 1.0.2 and Python 3.6.6.

Upvotes: 2

Views: 1903

Answers (1)

Stephen Rauch
Stephen Rauch

Reputation: 49794

You can do something like this:

for post_dict in posts:
    db.session.add(Post(**post_dict))
db.session.commit()

The ** magic is explained (Here).

Upvotes: 3

Related Questions