gromiczek
gromiczek

Reputation: 3020

Why an UnmappedInstanceError while populating a database using Flask-SQLAlchemy?

I'm new to SQLAlchemy and am using Flask-SQLAlchemy for my current project. I'm getting an error that has me stumped:

sqlalchemy.orm.exc.UnmappedInstanceError: Class 'flask_sqlalchemy._BoundDeclarativeMeta' is not mapped; was a class (app.thing.Thing) supplied where an instance was required?

I've tried changing the notation in the instatiation, and moving some things around. Could the problem be related to this question, or something else?

Here is my module (thing.py) with the class that inherits from Flask-SQLAlchemy's db.Model (like SQLAlchemy's Base class):

from app import db

class Thing(db.Model):
    indiv_id = db.Column(db.INTEGER, primary_key = True)
    stuff_1 = db.Column(db.INTEGER)
    stuff_2 = db.Column(db.INTEGER)
    some_stuff = db.Column(db.BLOB)

    def __init__():
        pass

And here is my call to populate the database in the thing_wrangler.py module:

import thing
from app import db

def populate_database(number_to_add):
    for each_thing in range(number_to_add):
        a_thing = thing.Thing
        a_thing.stuff_1 = 1
        a_thing.stuff_2 = 2
        a_thing.some_stuff = [1,2,3,4,5]
        db.session.add(a_thing)
    db.session.commit()

Upvotes: 4

Views: 10973

Answers (1)

davidism
davidism

Reputation: 127190

You need to create an instance of your model. Instead of a_thing = thing.Thing, it should be a_thing = thing.Thing(). Notice the parentheses. Since you overrode __init__, you also need to fix it so it takes self as the first argument.

Upvotes: 8

Related Questions