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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With