1

I have a list of dictionaries with three keys in each dictionary (title, url, score).

I would like to save each dictionary as a separate instance of a db model using sqlalchemy (i'm using sqlite3).

My list of dictionaries is saved into a variable called 'final'

Here is my db.Model:

class Favorite(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    tile = db.Column(db.String(100))
    url = db.Column(db.String(150))
    score = db.Column(db.Integer)
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'))

    def __init__(self, title, url, score):
        self.title = title
        self.url = url
        self.score = score

As for my logic, this is what I have tried so far:

for post in final:
    db.session.add(post)
    db.session.commit()

I've been getting the following error when running the program with this code:

UnmappedInstanceError: Class '__builtin__.dict' is not mapped

1 Answer 1

1

You have to construct instances of Favorite from each dict in the final list and then add it to session and commit.

for post in final:
  fav=Favorite(title=post.get('title'),url=post.get('url'),score=post.get('score'))
  db.session.add(fav)
  db.session.commit()
Sign up to request clarification or add additional context in comments.

1 Comment

thank you, I knew I could commit each dictionary but for some reason couldn't think of the title=post.get('') logic that you provided. thank you again

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.