Exclude object from SQLAlchemy session

I want to pass an instance of the mapped class to a method other than SQLAlchemy (in another process), and I only need the values ​​of my attributes. The problem is that the UnboundExecutionError event UnboundExecutionError , every time the method wants to read the attribute value. I understand why this is happening, but I would like to have a solution to this problem.

I only need the values ​​of my specific attributes (id, name and dirty in the example) and I do not need the SQLAlchemy overhead in the assignment method.

Class class:

 Base = declarative_base() class Record(Base): __tablename__ = 'records' _id = Column('id', Integer, primary_key=True) _name = Column('name', String(50)) _dirty = Column('dirty', Boolean, index=True) @synonym_for('_id') @property def id(self): return self._id @property def name(self): return self._name @name.setter def name(self, value): self._name = value self._dirty = True name = synonym('_name', descriptor=name) @synonym_for('_dirty') @property def dirty(self): return self._dirty 

Call example:

 ... def do_it(self): records = self.query.filter(Record.dirty == True) for record in records: pass_to_other_process(record) 

I tried using session.expunge() and copy.copy() , but to no avail.

+6
python sqlalchemy
source share
2 answers

I assume that you are facing the problem of lazy loading SQLAlchemy. Since I really don't know much about SQLAlchemy internals, here's what I recommend:

 class RecordData(object): __slots__ = ('id', 'name', 'dirty') def __init__(self, rec): self.id = rec.id self.name = rec.name self.dirty = rec.dirty 

Then later ...

 def do_it(self): records = self.query.filter(Record.dirty == True) for record in records: pass_to_other_process(RecordData(record)) 

Now I think there is a way to tell SQLAlchemy to turn your object into a "dumb" object that has nothing to do with the database and is very similar to what I just did here. But I do not know what it is.

+5
source share

You need to remove the ALchemy SQL object from the aka 'expunge' it session. You can then request any attribute already loaded without reusing its last known session / unrelated session.

 self.expunge(record) 

Remember that any attribute uploaded will return the last known value, or None. If you want to work with the object again later, you can simply call 'add' or 'merge' again

 self.add(record) 
+10
source share

All Articles