Object Persistence in SqlAlchemy - Adding Self to a database
<p>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:</p>

<pre><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()
</code></pre>

<p>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.  </p>

<p>However, with this approach I get an UnmappedInstanceError : "Class '<strong>builtin</strong>.str' is not mapped.  </p>

<p>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?</p>

<p>Take a look at signature of <a href="http://docs.sqlalchemy.org/en/latest/orm/session_api.html#sqlalchemy.orm.session.Session.add" rel="nofollow"><code>session.add</code></a> method:</p>

<pre><code>add(instance, _warn=True)
</code></pre>

<p>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 <a href="http://docs.sqlalchemy.org/en/latest/orm/tutorial.html#declare-a-mapping" rel="nofollow">declared a mapping</a> for this class. So the right way store this object is:</p>

<pre><code>session.add(self)
</code></pre>

<p>The error message that you got means that you tried to add to session an instance of <code>str</code> and there is no mapping to any table in database declared for this datatype.</p>

python sqlalchemy