views:

433

answers:

2

Hi,

I want to map a Tag entity using declarative method with sqlachemy. 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 add the "parent" relationship?

Thanks

+1  A: 

parent = relation('Tag') — see http://www.sqlalchemy.org/docs/05/reference/ext/declarative.html#configuring-relations.

PiotrLegnica
I try this, but give me an error:sqlalchemy.exc.ArgumentError: Could not determine join condition between parent/child tables on relationship Tag.parent. Specify a 'primaryjoin' expression. If this is a many-to-many relationship, 'secondaryjoin' is needed as well.Thanks
Hugo
+3  A: 

You add a foreign key referencing the parent, and then create a relation 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 = relation('Tag', remote_side=[id])

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

Ants Aasma
Works like a charm!
Hugo