It is a recurrent problem that is displays tree-like structures like
threaded comments. For example:
db.define_table('post',
Field('parent_id','reference post'),
Field('body'))
where each comment has a body and a parent_id (parent_id==None for the root
comment(s))
We can populate the comments with some dummy data:
def make_up_data():
import random, uuid
ids = [None]
for k in range(100):
ids.append(db.post.insert(parent_id=random.choice(ids),
body=str(uuid.uuid4())))
if k==0:
ids.pop(None)
if db(db.post).isempty(): make_up_data()
The new feature in trunk allows you to select the comments are organized
them into trees.
roots = db(db.post).select().as_trees()
This returns a list of parent nodes. Each not stores its own children,
recursively.
Now you can print them all using a tree traversal:
def show(row,n=0):
return ' '*n+row.body+'\n'+''.join(show(c,n+1) for c in
row.children)
print show(roots[0])
Notice you can specify the name of the parent field:
roots = db(db.post).select().as_trees(parent_name="parent_id")
Please let me know if you think this can be improved.
--
Resources:
- http://web2py.com
- http://web2py.com/book (Documentation)
- http://github.com/web2py/web2py (Source code)
- https://code.google.com/p/web2py/issues/list (Report Issues)
---
You received this message because you are subscribed to the Google Groups
"web2py-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
For more options, visit https://groups.google.com/groups/opt_out.