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?
You add a
ForeignKeyreferencing the parent, and then create a relationship that specifies the direction viaremote_side. This is documented under adjacency list relationships. For declarative you’d do something like this:If you want the reverse relation also, add
backref='children'to the relationship definition.