1

I am following the following tutorial on displaying hierarchical data from database http://docs.sqlalchemy.org/en/rel_0_7/orm/relationships.html#adjacency-list-relationships

so far i have the following table

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])

And the following entries in 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

I want to retrieve data in a format that will be suitable for comments e.g root -> child1 -> child2 ->(subchild1->subchild2)->child4

So far i have been able to retrieve the children of a parent through this query

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
....

I want to group this results in the following manner

root
....
child1
....
child2
subchild1
subchild 2
....
child3
....
child4
....
4

1 回答 1

0

为了在没有他的孩子的情况下获得根,您应该使用 OUTER JOIN 而不是 INNER JOIN。

要按父母对孩子进行分组,您应该使用 GROUP BY。

因此,您的查询将是:

  qry = session.query(nodealias,Node).\
        outerjoin(nodealias, Node.parent).\
        group_by(Node.parent).all()

然后,要在您的第一级叶子之间设置分隔符,您必须在遍历结果时对 parent.id 进行测试。不要忘记检查 NoneType 父级,因为您在结果集中包含根。

  for parent, child in qry:
    if parent is None or parent.id != 1:
      print child.data
    else:
      print '...'
      print child.data

为了更好地表示 3 级叶子,您可以通过检查 parent.id != 2 来应用类似的技术。

希望这会帮助你。

于 2012-10-18T17:09:40.297 回答