Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLALchemy adjacency list get all parents

Here's an adjacency list example:

class TreeNode(Base):
    __tablename__ = 'tree'
    id = Column(Integer, primary_key=True)
    parent_id = Column(Integer, ForeignKey(id))
    name = Column(String(50), nullable=False)

    children = relationship("TreeNode",
                        cascade="all",
                        backref=backref("parent", remote_side=id)
                    )

Supposing I've got a simple linear structure: (0)---->(1)---->(2)---->(3)

How do I get all ancestor nodes of a certain node? Something like node2.parents.all() that returns a list of nodes 0 and 1.

I tried to do this:

parents = relationship("TreeNode", cascade="all", primaryjoin="TreeNode.parent_id==TreeNode.id")

with no luck - it returns children instead of parents.

Thanks.

like image 432
rocknrollnerd Avatar asked Nov 15 '25 12:11

rocknrollnerd


1 Answers

Thank you, I'll look it up - for now it seems to be a little bit dark. If someone else's stumbled on this, it's possible to use rather more exprensive thing which still does what I want:

@property
def parents(self):
    allparents = []
    p = self.parent
    while p:
        allparents.append(p)
        p = p.parent
    return allparents
like image 141
rocknrollnerd Avatar answered Nov 17 '25 09:11

rocknrollnerd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!