Steve Novosel Steve Novosel -4 years ago 212
Python Question

save list of dictionaries to database using flask-sqlalchemy

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(''))

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:

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

UnmappedInstanceError: Class '__builtin__.dict' is not mapped

Answer Source

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:
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download