2016-11-11 1 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") 

나는 노드 객체가이 클래스 정의에 의해 많은 아이를 가질 수있어. 내 이해는 노드 객체를 만들고 저장할 때 레코드 (id, parent_id, data)가 데이터베이스에 삽입 될 때, 나는 id이 기본적으로 생성된다는 것을 알지만 어떻게 parent_id이 생성됩니까? 내 프로젝트에서 비슷한 사용법을 시도했지만 parent_idNone으로 유지됩니다.

답변

1

parent_id 실제로 생성되지는 않지만 개체간에 실제 관계을 사용하여 할당됩니다. 즉, sqlalchemyparent_id을 모든 어린이들에게 Node.children으로 적절히 저장할 것입니다.

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() 
: 다음과 같은 방법으로 코드를 작성할 수 있습니다

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

:

는 예를 들어, 관계 그래프를 달성하기 위해 sqlalchemy의 문서에 설명 된대로 링크

관련 문제