Getting child elements that are related to a parent in same table
- by Madawar
I have the following database schema
class posts(Base):
__tablename__ = 'xposts'
id = Column(Integer, primary_key=True)
class Comments(Base):
__tablename__ = 'comments'
id = Column(Integer, primary_key=True)
comment_parent_id=Column(Integer,unique=True)
#comment_id fetches comment of a comment ie the comment_parent_id
comment_id=Column(Integer,default=None)
comment_text=Column(String(200))
Values in database are
1 12 NULL Hello First comment
2 NULL 12 First Sub comment
I want to fetch all Comments and sub comments of a post using sqlalchemy and have this so far
qry=session.query(Comments).filter(Comments.comment_parent_id!=None)
print qry.count()
Is there a way i can fetch the all the subcomments of a comment in a query i have tried outerjoin on the same table(comments) and it seemed stupid and it failed.