Sqlalchemy:跨多个(链接)关系传播更新

时间:2014-08-03 18:39:53

标签: orm sqlalchemy relationship

我在这里展示了三个链接表的(人工)示例: ParentA,ChildA ChildAA ChildA 通过外键与 ParentA 的主键(PK)相关, ChildAA ChildA <中的相同键相关/ em>的。通过这种方式, ChildAA 链接到 ParentA 的主键。我希望当我对 ParentA PK进行更改时,此更改会传播回相应的 ChildAA 的属性,但事实并非如此。

提前致谢!

(如果之前已经回答或记录过,我很抱歉,我真的找不到任何东西。)

守则:

from sqlalchemy import *
from sqlalchemy import orm
from sqlalchemy.ext.declarative import declarative_base

Base = declarative_base()


class ParentA(Base):
    __tablename__ = 'tbl_parentA'    

    pid = Column(Integer, primary_key=True)

    childA = orm.relationship("ChildA", passive_updates=False, backref='parentA')


class ChildA(Base):
    __tablename__ = 'tbl_childA'    

    attrib1 = Column(String, nullable=True)
    parentA_id = Column(Integer, ForeignKey(ParentA.pid), primary_key=True)

    childAA = orm.relationship("ChildAA", passive_updates=False, backref="childA")


# This class is related to Parents through ChildA
class ChildAA(Base):
    __tablename__ = 'tbl_childAA'    

    cid = Column(Integer, primary_key=True)

    attrib1 = Column(String, nullable=True)

    parentA_id = Column(Integer, ForeignKey(ChildA.parentA_id))


def clear_db(db):
    tmp = db.echo
    db.echo = False

    metadata = MetaData(bind=db)
    metadata.reflect(db)

    for table in reversed(metadata.sorted_tables):
        table.drop(db)

    metadata.clear()

    db.echo = tmp


if __name__ == '__main__':

#    SQLite Connection
    db = create_engine('sqlite:///linked_updates.db')
#   db.echo = True

#    Initalize Objects
    pa1 = ParentA()

    ca1 = ChildA(attrib1='ca1 str')
    caa1= ChildAA(attrib1='caa1 str')

#    Assign a parent to ChildA
    ca1.parentA = pa1

#    Assign a parent to ChildAA
    caa1.childA = ca1

#    Initialize clean DB & session
    clear_db(db)   
    Base.metadata.create_all(db)    
    session = orm.create_session(db)


#    Write to DB   
    session.add_all([pa1, ca1, caa1])
    session.flush()
    print 'After flush, we have: ', caa1.parentA_id, '==', caa1.childA.parentA_id

#    Induce change, check propagation
    pa1.pid = 2

    session.flush()

    print 'I expect: ', caa1.parentA_id, '==', caa1.childA.parentA_id

    print 'END'

0 个答案:

没有答案