我想将映射类的实例传递给一个非SQLAlchemy感知方法(在另一个进程中),并且只需要我属性的值即可。问题是,每当该方法要读取属性值时,就会出现UnboundExecutionError。我确实知道为什么会发生这种情况,但是我想对此问题有一个解决方案。

我只需要定义的属性的值(在示例中为id,name和dirty),并且在目标方法中不需要SQLAlchemy开销。

示例类:

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

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

我尝试使用session.expunge()copy.copy(),但是没有成功。

最佳答案

我的猜测是您正在运行SQLAlchemy的延迟加载。由于我实际上对SQLAlchemy的内部知识并不了解很多,因此,我建议您这样做:

class RecordData(object):
    __slots__ = ('id', 'name', 'dirty')

    def __init__(self, rec):
        self.id = rec.id
        self.name = rec.name
        self.dirty = rec.dirty

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

现在,我认为有一种方法可以告诉SQLAlchemy将您的对象变成一个“哑”对象,该对象与数据库没有连接,并且看起来很像我在这里所做的。但是我不知道那是什么。

关于python - 从SQLAlchemy session 中删除对象,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3822726/

10-12 16:43
查看更多