Warm tip: This article is reproduced from stackoverflow.com, please click
python python-3.x

Get all tree sub items using recursion

发布于 2020-03-27 10:20:58

I have a tree of items inside each other and i want when i choose a leaf i got all sub items in order.

For example i have product A which have sub product B&C and product B Have other 2 products D,E and product C have 3 products F&G&S and product D have 2 product H,I

so i need when i select Product A i got the sub tree numbered

1.A
1.1.B
1.1.1.D
1.1.1.1.H
1.1.1.2.I
1.1.2.E
1.2.C
1.2.1.F
1.2.2.G
1.2.3.S

I tried to solve this with recursion but still have issues numbering. Here is what i have tried:

PRODUCT_LIST = []
class MyClass(object):
    PRODUCT_LEVEL=0

    def _get_sub_levels(self, product_id, level='1'):
        new_level = 1
        # product_accessory_ids is product sub products
        for item in product_id.product_accessory_ids:
            level = level + '.' + str(new_level)
            PRODUCT_LIST.append(
                {'level': level, 'products': item})
            if item.product_id.product_tmpl_id.product_accessory_ids:
                new_level += 1

                self._get_sub_levels(item.product_id.product_tmpl_id, level=level)
            else:
                PRODUCT_LIST.append(
                    {'level': level, 'products': product_id.product_accessory_ids})
        else:
            PRODUCT_LIST.append(
                {'level': level, 'products': product_id.product_accessory_ids})
            # new_level+=1
            # level = level +'.'+ str(new_level)
            # PRODUCT_LIST.append(
            #     {'level': level, 'products': product_id.product_accessory_ids})
            # if item.product_id.product_tmpl_id.product_accessory_ids:
            #     new_level = '.1'
            #     level = level + new_level
            #     self._get_sub_levels(item.product_id.product_tmpl_id, level=level)
        return PRODUCT_LIST

    product_list = _get_sub_levels(product_id, str(PRODUCT_LEVEL))
Questioner
Mostafa Mohamed
Viewed
94
Mostafa Mohamed 2019-07-03 19:13

I solved my issue .. here is the soluation :

first i get the level of the first Product A either if it's 1,2.. in the selection then i pass the it to the _get_sub_levels:


    def _get_sub_levels(self, product_id):
        accessories = product_id.product_accessory_ids
        product_list = []
        depth = [1]

        def wrapped(product_id):
            depthStr = '.'.join([str(i) for i in depth])
            product_list.append(
                {'level': depthStr, 'products': [product_id]})

            depth.append(1)
            for child in product_id.product_id.product_tmpl_id.product_accessory_ids:
                wrapped(child)
                depth[-1] += 1
            depth.pop()

        for accessory in accessories:
            wrapped(accessory)
            depth[0] += 1
        return product_list