Select recursivo web2py

db.define_table('thing',
                    Field('name'),
                    Field('owner_id', 'reference person'))
person =  db.person(id)
for thing in person.thing.select(orderby=db.thing.name):
    print person.name, 'owns', thing.name
roots = { 1: {'id':1, 'name': 'Paul', 'childreen': {
    3: {'id': 3, 'name': 'Jessica', 'childreen': {}
   ,8: {'id': 8, 'name': 'Robert', 'childreen': {...}
}
rows = db(db.person).select().as_dict()
roots = {}# Pre order algorithm
def pre_order(node):
    for k, v in rows.items():
        if node['id'] == v['owner_id']:
            if 'childreen' not in node:
                node['childreen'] = {}
            node['childreen'][k] = v
            del rows[k]
            pre_order(v)# Filter fathers
for k, v in rows.items():
    if v['owner_id']==None:
        del rows[k]
        # Now search by son
        pre_order(v)
        roots[k] = v

Comentários

Postagens mais visitadas deste blog

Web2py com NGINX

Configurar o web2py no Apache e Ubuntu LTS

API RESTFul no web2py