2016-11-11 94 views
1

我讀了SQLAlchemy文檔並獲得由給定的例子困惑:鄰接列表關係在SQLAlchemy中如何工作?

class Node(Base): 
    __tablename__ = 'node' 
    id = Column(Integer, primary_key=True) 
    parent_id = Column(Integer, ForeignKey('node.id')) 
    data = Column(String(50)) 
    children = relationship("Node") 

我知道一個Node對象可以通過這個類的定義有許多兒童。我的理解是在創建和保存一個Node對象的時候,一個記錄(id,parent_id,data)會被插入到數據庫中,我知道默認會生成id,但parent_id是怎麼產生的?我在我的項目中嘗試過類似的用法,但parent_id保持None

回答

1

parent_id並非真正生成,而是使用對象之間的實際關係進行分配。這就是說sqlalchemy會保存正確的parent_id給所有的孩子關係Node.children

例如,在以實現關係曲線圖中記錄的sqlalchemy的文檔中鏈接到:

root --+---> child1 
     +---> child2 --+--> subchild1 
     |    +--> subchild2 
     +---> child3 

可能寫在下面的方式代碼:

root = Node(
    data='root', 
    # @NOTE: all Node under this children will have `parent_id` point to the `id` of this (root) Node 
    children=[ 
     Node(data='child1'), 
     Node(data='child2', 
      children=[ 
       Node(data='subchild1'), 
       Node(data='subchild2'), 
      ]), 
     Node(data='child3') 
    ] 
) 

session.add(root) # this will also add all the other nodes in the graph 
session.commit()