Reputation: 584
I have an object which I am trying to add persistence to using sqlalchemy to allow for a local lookup of the object if I've already created an instance of it before. Within the init statement for the object, I have the following code:
persistent = session.query(exists().where(myobject.myfield==self.myfield)).scalar()
if not persistent:
self.create_object_from_scratch()
session.add(myfield, self)
session.commit()
else:
self.utilize_object_in_database()
As per the above, the object can determine if it is already in the database by whether the primary key myfield is in the database. If it is not, I would like to create the object and then add it into the session and commit. The database structure that I've set up is just two columns... a primary key (string) and a BLOB which is supposed to represent my 'object' for retrieval.
However, with this approach I get an UnmappedInstanceError : "Class 'builtin.str' is not mapped.
My question is, given what I am trying to accomplish here (persistence of a python object) am I approaching this correctly/efficiently? Is it possible to add 'self' into a database as a BLOB using sqlalchemy?
Upvotes: 0
Views: 676
Reputation: 3740
Take a look at signature of session.add
method:
add(instance, _warn=True)
As you can see, you need to pass instance of class that you want to store. There is no need to specify primary key because you already did it when you declared a mapping for this class. So the right way store this object is:
session.add(self)
The error message that you got means that you tried to add to session an instance of str
and there is no mapping to any table in database declared for this datatype.
Upvotes: 1