Python 获取与同一表中的父元素相关的子元素

Python 获取与同一表中的父元素相关的子元素,python,mysql,sqlalchemy,Python,Mysql,Sqlalchemy,我有以下数据库模式 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=Tr

我有以下数据库模式

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))
数据库中的值是

1   12  NULL    Hello First comment
2   NULL    12  First Sub comment
我想使用sqlalchemy获取一篇文章的所有评论和子评论,到目前为止,我已经完成了这项工作

qry=session.query(Comments).filter(Comments.comment_parent_id!=None)
print qry.count()
有没有一种方法可以在查询中获取注释的所有子元素?我在同一个表(注释)上尝试了outerjoin,但它似乎很愚蠢,失败了。

您在sqlalchemy查询中使用了all()函数,然后可以使用count和len来查找数据库中的总行。 因为此查询提供了二维列表结果

qry=session.query(Comments).filter(Comments.comment_parent_id!=None).all()

len(qry)

sqlalchemy的文档中有一个很好的例子,用于自引用foreignkey:我可以得到一个outerjoin示例吗?因为连接不能工作,因为注释可能缺少子元素?len(qry)部分到目前为止并不重要,我只是测试是否返回了结果。