Jason
Jason

Reputation: 726

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.

Upvotes: 3

Views: 1414

Answers (1)

van
van

Reputation: 77012

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

Upvotes: 1

Related Questions