Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLAlchemy - Mapping self-referential relationship as one to many (declarative form)

I want to map a Tag entity using declarative method with SQLAlchemy. A tag can have a parent (another Tag).

I have:

class Tag(Base):     __tablename__ = 'tag'      id = Column(Integer, primary_key=True)     label = Column(String)      def __init__(self, label, parentTag=None):         self.label = label 

How can I add the "parent" relationship?

like image 787
Hugo Avatar asked Apr 14 '10 14:04

Hugo


1 Answers

You add a ForeignKey referencing the parent, and then create a relationship that specifies the direction via remote_side. This is documented under adjacency list relationships. For declarative you'd do something like this:

class Tag(Base):     __tablename__ = 'tag'      id = Column(Integer, primary_key=True)     label = Column(String)     parent_id = Column(Integer, ForeignKey('tag.id'))      parent = relationship('Tag', remote_side=[id]) 

If you want the reverse relation also, add backref='children' to the relationship definition.

like image 199
Ants Aasma Avatar answered Sep 20 '22 17:09

Ants Aasma