1. 程式人生 > >SQLAlchemy一對多和多對一

SQLAlchemy一對多和多對一

SQLAlchemy中的對映關係有四種,分別是一對多,多對一,一對一,多對多

一對多(one to many):

因為外來鍵(ForeignKey)始終定義在多的一方.如果relationship定義在多的一方,那就是多對一,一對多與多對一的區別在於其關聯(relationship)的屬性在多的一方還是一的一方,如果relationship定義在一的一方那就是一對多.  這裡的例子中,一指的是Parent,一個parent有多個child:

class Parent(Base):
    __tablename__ = 'parent'
    id = Column(Integer,primary_key = True)
    children = relationship("Child",backref='parent')

class Child(Base):
    __tablename__ = 'child'
    id = Column(Integer,primary_key = True)
    parent_id = Column(Integer,ForeignKey('parent.id'))

多對一(many to one):

這個例子中many是指parent了,意思是一個child可能有多個parent(父親和母親),這裡的外來鍵(child_id)和relationship(child)都定義在多(parent)的一方:

class Parent(Base):
    __tablename__ = 'parent'
    id = Column(Integer, primary_key=True)
    child_id = Column(Integer, ForeignKey('child.id'))
    child = relationship("Child", backref="parents")

class Child(Base):
    __tablename__ = 'child'
    id = Column(Integer, primary_key=True)

為了建立雙向關係,可以在relationship()中設定backref,Child物件就有parents屬性.設定 cascade= ‘all’,可以級聯刪除:

class Parent(Base):
    __tablename__ = 'parent'
    id = Column(Integer,primary_key = True)
    children = relationship("Child",cascade='all',backref='parent')

def delete_parent():
    session = Session()
    parent = session.query(Parent).get(2)
    session.delete(parent)
    session.commit()

不過不設定cascade,刪除parent時,其關聯的chilren不會刪除,只會把chilren關聯的parent.id置為空,設定cascade後就可以級聯刪除children