Skip to Content
Menu
This question has been flagged
1 Reply
14157 Views

Hi everyone,

I am trying to create a Python function that maps nodes of a web created by Odoo relational fields, and returns such map as a dictionary. 

I'll try to explain. 


Let us consider the model 'account.account', and its fields 'child_parent_ids' (o2m to same class) and 'parent_id' (m2o to same class, inverse of previous field). 

How can I create a dictionary where every key is a record of 'account.account', and every key's values are dictionaries made of their children records recursively, or 'True' if such record has no child records? 


E.g., let us consider this web:

account

|

|_child-1

|

|_child-2

|            |

|            |_child-21

|            |_child-22

|            |_child-23

|

|_child-3

|             |

|             |_child-31

|             |_child-32

|             |              |

|             |              |_child-321

|             |              |_child-322

|             |              |_child-323

|             |              |_child-324

|             |

|             | _child-33

|

|_child-4

 

The function I'm looking for should return a dictionary like this:

{'account':

    {'child-1': True},

    {'child-2':

        {'child-21': True},

        {'child-22': True},

        {'child-23': True},

    },

    {'child-3':

        {'child-31': True},

        {'child-32':

            {'child-321': True},

            {'child-322': True},

            {'child-323': True},

            {'child-324': True}

        },

        {'child-33': True},

    }

    {'child-4': True},

}

 

I tried to create a recursive function as follows:


@api.multi

def get_tree_dict(self):

    tree_dict = {}

    if self.child_parent_ids:

        for child in child_parent_ids:

        tree_dict[self] = child.get_tree_dict()

    return tree_dict

    else:

        tree_dict[self] = True

        return tree_dict

 

It doesn't seem to work, and I can't find out why (please don't be too hard on me).

Can please anyone help me, by showing the error I'm making and how can I solve it?

Please note that the depth of the dictionary is not known a priori, so I think the method should be recursive (or iterative).

Avatar
Discard
Best Answer

Dear SLYK;

Try to make this by using while , that better to make recursive , but you need  the Right Condition to prevent infinite loop.

I hope I helped you...

Avatar
Discard
Related Posts Replies Views Activity
1
Oct 22
4667
2
Nov 17
4955
3
Jul 19
13305
0
Sep 16
2953
3
Oct 15
17541