db.Model
呼び出されたページから取得したリストに基づいてツリー構造を構築しています。
各ページ エントリには、sortIndex と呼ばれる parentKey プロパティがありdb.SelfReferenceProperty()
ますdb.IntegerProperty()
。
リストをフェッチし、メソッドを呼び出してリストをトラバースし、ネストされた dict をツリーとして作成します。リスト全体を取得する理由は、複数のクエリをスキップしたいからです。
pages = Pages.gql('ORDER BY sortIndex').fetch(1000)
build_tree(pages)
そしてbuild_tree:
def build_tree(nodes, *args):
# create empty tree to fill
tree = {}
build_tree_recursive(tree, None, nodes, *args)
return tree
def build_tree_recursive(tree, parent, nodes, *args):
# find root children, first level nodes have no parentKey
if parent is None:
children = [n for n in nodes if n.parentKey == None]
# find children
else:
children = [n for n in nodes if n.parentKey is not None and n.parentKey.key() == parent]
# build a subtree for each child
for child in children:
# start new subtree
key = child.key()
# Use page entry key as unique dict key
tree[key] = { 'page' : child, 'children' : {}}
# call recursively to build a subtree for current node
build_tree_recursive(tree[key]['children'], key, nodes)
問題は、リストが再配置され、det ORDER BY に従わないことです。これは、適切な親が見つかったときに各ページがリストに入れられるためだと思います。しかし、最初のレベル ( を持つページparentKey == None
) でさえ間違った順序で返されます。
tree[str(i) + '_' + str(key)] のループ カウンターを使用してプレフィックスを設定しようとしましたが、適切な順序で返されませんでした。
では、それらを適切な順序で取得する方法について質問します。
編集[解決済み]:
下記参照