下面是关于显示来自数据库http://docs.sqlalchemy.org/en/rel_0_7/orm/relationships.html#adjacency-list-relationships的分层数据的教程
到目前为止,我有下表
class Node(Base):
__tablename__ = 'node'
id = Column(Integer, primary_key=True)
parent_id = Column(Integer, ForeignKey('node.id'))
data = Column(String(50))
parent = relationship("Node", remote_side=[id])
以及mysql中的以下条目
id parent_id data
1 NULL root
2 1 [->] child1
3 1 [->] child2
4 3 [->] subchild1
5 3 [->] subchild 2
6 1 [->] child3
7 NULL root2
8 NULL root3
9 7 [->] subchild0froot2
10 8 [->] subchildofroot3
11 1 [->] child4
我想以适合注释的格式检索数据,例如root->;child1->;child2->;(subchild1->;subchild2)->;child4
到目前为止,我已经能够通过这个查询检索父对象的子对象
nodealias = aliased(Node)
qry = session.query(nodealias,Node).\
join(nodealias, Node.parent).\
filter(and_(Node.postid==45))
print qry
for x,y in qry:
print x.data
print y.data
print "...."
And it displays
root
child1
....
root
child2
....
child2
subchild1
....
child2
subchild 2
....
root
child3
....
root
child4
....
我想按以下方式对这些结果进行分组
root
....
child1
....
child2
subchild1
subchild 2
....
child3
....
child4
....
要获得没有子级的根,应该使用外部连接而不是内部连接。你知道吗
要按父级对子级进行分组,应使用分组依据。你知道吗
因此,您的查询将是:
然后,要在你的第一级叶子上做一个测试父id在遍历结果时。不要忘记检查NoneType parent,因为您的结果集中包含了根。你知道吗
为了更好地用第三级leaf表示,您可以通过检查父id!= 2. 你知道吗
希望这对你有帮助。你知道吗
相关问题 更多 >
编程相关推荐