Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQLAlchemy - Parent child relationship in the same table

I want to have a parent child relationship in the same table. Below is what I have, and it isn't working. By "not working", I meant that when I call .children on some Item object, it gives me []. What is the error in my code and how to do it correctly? Thanks.

parents_children = Table('parents_children', Base.metadata,
                         Column('parent_id', bigint, ForeignKey('items.id', name='a'), primary_key=True),
                         Column('child_id', bigint, ForeignKey('items.id', name='b'), primary_key=True)
                         )

class Item(Base):
    __tablename__ = 'items'
    id = Column(bigint, primary_key=True, autoincrement=True)
    name = Column(types.String(80), default="")
    display_name = Column(types.String(80), default="")
    version = Column(types.String(80), default="")
    discriminator = Column(item_tag_enum, nullable=False)
    children = relationship('Item',
                            secondary=parents_children,
                            primaryjoin=id == parents_children.c.parent_id,
                            secondaryjoin=id == parents_children.c.child_id,
                            backref='parents')
    __mapper_args__ = {'polymorphic_on' : discriminator}

 # Item subclasses omitted because that's irrelevant to the question.
like image 627
missingfaktor Avatar asked Nov 04 '22 14:11

missingfaktor


1 Answers

I think there is an easier way... (this is how I do it)

def adopt(parent_id,child_id):
    parent = DBSession.query(Item).get(parent_id)
    child  = DBSession.query(Item).get(child_id)
    parent.children.append(child)
like image 161
Sheena Avatar answered Nov 09 '22 16:11

Sheena