排除自引用关系SQLAlchemy中的软删除项

Osc*_*ord 13 python sql sqlalchemy

我目前在以下方面有自我参照关系Foo:

parent_id = DB.Column(DB.Integer, DB.ForeignKey('foo.id'))

parent = DB.relation(
    'Foo', 
    remote_side=[id], 
    backref=DB.backref(
        'children', 
        primaryjoin=('and_(foo.c.id==foo.c.parent_id, foo.c.is_deleted==False)')
    )
)
Run Code Online (Sandbox Code Playgroud)

现在我试图排除任何is_deleted设置为true的孩子.我很确定问题是它是在检查is_deleted父母,但我不知道从哪里开始.

如何修改关系以使子项is_deleted不包含在结果集中?

pi.*_*pi. 3

我尝试着回答这个问题。我的解决方案应该适用于 SQLAlchemy>=0.8。

实际上,这里发生的事情并不令人惊讶,但在使用此类模式时必须小心谨慎,因为身份映射的状态Session不会始终反映数据库的状态。

我使用post_update中的开关来relationship打破此设置所产生的循环依赖性。有关详细信息,请参阅有关此的 SQLAlchemy 文档

警告:事实上,Session并不总是反映数据库的状态可能会导致严重的错误和其他混乱。在这个例子中,我用来expire_all显示数据库的真实状态,但这不是一个好的解决方案,因为它重新加载所有对象并且所有未flush更改的更改都会丢失。使用expireexpire_all小心!

首先我们定义模型

#!/usr/bin/env python
import sqlalchemy as sa
import sqlalchemy.orm as orm
from sqlalchemy.ext.declarative import declarative_base

engine = sa.create_engine('sqlite:///blah.db')
Base = declarative_base()
Base.bind = engine

class Obj(Base):
    __table__ = sa.Table(
        'objs', Base.metadata,
        sa.Column('id', sa.Integer, primary_key=True),
        sa.Column('parent_id', sa.Integer, sa.ForeignKey('objs.id')),
        sa.Column('deleted', sa.Boolean),
    )

    # I used the remote() annotation function to make the whole thing more
    # explicit and readable.
    children = orm.relationship(
        'Obj',
        primaryjoin=sa.and_(
            orm.remote(__table__.c.parent_id) == __table__.c.id,
            orm.remote(__table__.c.deleted) == False,
        ),
        backref=orm.backref('parent',
                            remote_side=[__table__.c.id]),
        # This breaks the cyclical dependency which arises from my setup.
        # For more information see: http://stackoverflow.com/a/18284518/15274
        post_update=True,
    )

    def __repr__(self):
        return "<Obj id=%d children=%d>" % (self.id, len(self.children))
Run Code Online (Sandbox Code Playgroud)

然后我们尝试一下

def main():
    session = orm.sessionmaker(bind=engine)
    db = session()
    Base.metadata.create_all(engine)

    p1 = Obj()
    db.add(p1)
    db.flush()

    p2 = Obj()
    p2.deleted = True

    p1.children.append(p2)
    db.flush()

    # prints <Obj id=1 children=1>
    # This means the object is in the `children` collection, even though
    # it is deleted. If you want to prevent this you may want to use
    # custom collection classes (not for novices!).
    print p1

    # We let SQLalchemy forget everything and fetch the state from the DB.
    db.expire_all()

    p3 = db.query(Obj).first()

    # prints <Obj id=1 children=0>
    # This indicates that the children which is still linked is not
    # loaded into the relationship, which is what we wanted.
    print p3

    db.rollback()


if __name__ == '__main__':
    main()
Run Code Online (Sandbox Code Playgroud)