Sqlalchemy.orm.exc.unmappedinstanceerror In Flask
Solution 1:
When you are adding a non-model-object into the session, you will be getting UnmappedInstanceError
.
In your case, q
was probably an unicode string, not a model object. (It appears that you are using Python 2.x because in Python 3.x, it will say str), this was the line of the root cause for UnmappedInstanceError: Class '__builtin__.unicode' is not mapped
:
File "C:\Users\Me\repos\mandj2\app\views.py", line 170, in add_manentry
db.session.add(q)
Solution 2:
q = request.form['name']
# do for 12 more fields
db.session.add(q)
request.form['name']
will return a unicode value. Then, you do...
db.session.add(q)
The goal of the session is to keep track of Entities (Python objects), not individual unicode values as you seem to be trying to do it (See here for more on what the session does). Thus, you should be adding objects that have a mapping (such as a User
object as shown in the "Mapping" section of the ORM tutorial), but you're actually passing a simple unicode value
What you're using is just one part of SQLAlchemy: the ORM (Object-Relational Mapper). The ORM will try to do things like allow you to create a new python object and have the SQL automatically generaeted by "adding" the object to the session..
a = MyEntity()
session.add(a)
session.commit() # Generates SQL to do an insert for the table that MyEntity is for
Keep in mind that you can use SQLAlchemy without using the ORM functionality. You could just do db.execute('INSERT...', val1, val2)
to replace your already "naked" SQL. SQLAlchemy will provide you connection pooling, etc (although if you're using SQLite, you probably don't care about connection pooling).
If you want to understand Flask-SQLAlchemy, I would first recommend understanding how SQLAlchemy works (especially the ORM side) by trying it out using simple scripts (as shown in the tutorials. Then you'll understand how Flask-SQLAlchemy would work with it.
Solution 3:
If you are changing database see: You have to address to what item in the object you want to change. See below:
client = session.query(Clients).filter_by(id=client_id).one()
if request.method == 'POST':
new_name = request.form['form_name']
client.name = new_name
session.add(client)
session.commit()
As you can see in the 'client' object, we have "name" among other info inside the object. We want to directly change 'name' only, therefore you need to address to it. (client.name)
If you are adding new thing to database: Here when you add a new value to the database with orm, you need to specify the item in the object that is receiving the data. in this case (Client.name)
if request.method == 'POST':
new_name = request.form['form_name']
name = Clients(name=new_name)
session.add(name)
session.commit()
Hope that helps.
Post a Comment for "Sqlalchemy.orm.exc.unmappedinstanceerror In Flask"