Sqlalchemy中relationship的理解

“指向”

即定義一張表中的數據條目指向另一張表中的條目,建立這種有向的“指向”可以讓表以字段的方式查詢到被指向的條目(們),所以,如果要雙向查詢,就需要雙向指向。

One To Many

在“多”方表中添加“一”方的id作爲ForeignKey約束,爲查詢方便雙方均需要定義relationship()字段;

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

One To One

與One To Many區別不大,只要“一”方的relationship方法中添加一個"uselist=False"參數即可,uselist是一個標量屬性(a scalar attribute),其含義是“一”方對應另一張表的條目不使用列表。

class Parent(Base):
__tablename__ = 'parent'
id = Column(Integer, primary_key=True)
child = relationship("Child", uselist=False, back_populates="parent")

class Child(Base):
__tablename__ = 'child'
id = Column(Integer, primary_key=True)
parent_id = Column(Integer, ForeignKey('parent.id'))  # 多方纔有這個字段
parent = relationship("parent", back_populates="child") 
# 通常也會把backref用函數表示天機uselist=False參數,用以顯示指出。 
# parent = rlationship("parent", backref=backref("child", uselist=False))


Many To Many

藉助中間表完成,利用relationship支持的secondary參數,

association_table = Table('association', Base.metadata,
    Column('left_id', Integer, ForeignKey('left.id')),
    Column('right_id', Integer, ForeignKey('right.id'))
    )
    
class Parent(Base):
    __tablename__ = 'left'
    id = Column(Integer, primary_key=True)
    children = relationship("Child",
                            secondary=association_table,
                            back_populates="parents")
class Child(Base):
    __tablename__ = 'right'
    id = Column(Integer, primary_key=True)
    parents = relationship("Parent",
                            secondary=association_table,
                            back_populates="children")

注意,secondary可以接受'a callable that returns the ultimate argument,which is evaluated only when mappers are first used."即接受可執行參數,可以讓association_table 在稍晚的時候定義,甚至可以在所有模塊都初始化完成後,直到它可調用爲止。

class parent(Base):
    __tablename__ = "left"
    id = Column(Integer, primary_key=True)
    children = relationship("Child", 
                            secondary=lambda: assciation_table,
                            backref="parents")

以上relationship參數的表明均可以用類名字符串代替。

刪除Mang To Many記錄,不必手動刪除secondary的中間表數據,數據庫會根據“cascade rule”級聯規則自動刪除。


如果中間表對象需要被調用

class Association(Base):
    __tablename__ = 'association'
    left_id = Column(Integer, ForeignKey('left.id'), primary_key=True)
    right_id = Column(Integer, ForeignKey('right.id'), primary_key=True)
    extra_data = Column(String(50))
    child = relationship("Child", back_populates="parents")
    parent = relationship("Parent", back_populates="children")
class Parent(Base):
    __tablename__ = 'left'
    id = Column(Integer, primary_key=True)
    children = relationship("Association", back_populates="parent")
class Child(Base):
    __tablename__ = 'right'
    id = Column(Integer, primary_key=True)
    parents = relationship("Association", back_populates="child")
    
# create parent, append a child via association
p = Parent()
a = Association(extra_data="some data")
a.child = Child()
p.children.append(a)
# iterate through child objects via association, including association
# attributes
for assoc in p.children:
    print(assoc.extra_data)
    print(assoc.child)


# 尋找答案的路途上要保持耐心和專心!


需要注意:back_populates參數賦值參數一定不能是relationship第一個參數的字段,那樣相當於被對應關係表中有了重複字段。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章