2

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.

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.