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

Orm Sqlalchemy:跨多个(链接的)关系传播更新,orm,sqlalchemy,relationship,Orm,Sqlalchemy,Relationship,我在这里展示了三个链接表的(人工)示例:ParentA、ChildA和ChildAA。ChildA通过外键与ParentA的主键(PK)相关,ChildAA与ChildA中的同一个键相关。通过这种方式,ChildAA链接到ParentA的主键。我希望当我对ParentA PK进行更改时,此更改会传播回相应ChildAA的属性,但事实并非如此 提前谢谢 (很抱歉,如果之前已经回答或记录了此问题,我真的找不到任何东西。) 守则: from sqlalchemy import * from sqlal

我在这里展示了三个链接表的(人工)示例:ParentA、ChildA和ChildAA。ChildA通过外键与ParentA的主键(PK)相关,ChildAA与ChildA中的同一个键相关。通过这种方式,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'

你可以看看这场讨论,以及对我有效的解决方案。