Reputation: 3975
I'm currently trying to create sqlalchemy objects using the declarative approach that are "temporary" objects and are not meant to be persisted but simply compared.
As such, i would like to create them "outside" the current session. The problem is if i don't expunge them one by one, the session tries to flush them, and thus creates foreign key errors (which is normal because the objects are incomplete).
I've been using "declarative_base" from sqlalchemy.ext.declarative to create a base class, then inherit from it to create my model objects. eg (pseudo code) :
class BaseEntity(object):
... common columns ...
Base = declarative_base(cls=BaseEntity)
class MyObject(Base):
... other columns ..
Now whenever i do :
tmpobj = MyObject()
i need to do (with session object being a scoped_session declared in another module)
session.expunge(tmpobj)
which, given the complex way my tmp objects are created (and nested to each others), is really umbersome.
Is there any special parameter i could pass to MyObject() constructor to prevent the object from beeing added to the session ?
Upvotes: 1
Views: 1182
Reputation: 3975
Ok, so indeed, i was adding those tmp objects to managed objects, thus making them managed by the session as well.
The solution was to stop linking the tmp objects to managed objects using relationship, and use the foreign key columns instead (i still needed to keep the information).
So, instead of doing this (in this case, using a backref relationship):
mytmpobject.relationobject = aManagedRelationObject
do this :
mytmpobject.relationobject_id = aManagedRelationObject.id
This way, the mytmpobject stays outside the session.
Upvotes: 1