简体   繁体   中英

How does the Adjacency List Relationships works in SQLAlchemy?

I am reading the SQLAlchemy docs and get confused by the given example:

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")

I know a Node object can have many children by this class definition. My understanding is when creating and saving a Node object, a record (id, parent_id, data) will be inserted into the database, I know id will be generated by default, but how is the parent_id generated? I tried a similiar usage in my project, but the parent_id stays None .

parent_id is not really generated, it is assigned using the actual relationships between objects. This is to say that sqlalchemy will save proper the parent_id to all the children the relationship Node.children .

For example, in order to achieve the relationship graph as documented in the sqlalchemy 's documentation you link to:

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

you may write a code in the following way:

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM