如何在 Python 中创建一个递归函数来创建一个映射 Odoo 8 关系字段记录的字典?

How to create a recursive function in Python to create a dict which maps Odoo 8 relational field records?


我正在尝试创建一个 Python 函数来映射由 Odoo 关系字段创建的网络节点,并且 returns 这样的映射作为字典。
我会尽力解释。

让我们考虑模型 'account.account',及其字段 'child_parent_ids'(o2m 到相同的 class)和 'parent_id'(m2o 到相同的 class,与前一个字段相反) .
我如何创建一个字典,其中每个键都是 'account.account' 的记录,并且每个键的值都是由其子记录递归构成的字典,或者 'True' 如果此类记录没有子记录?

例如,让我们考虑这个网站:

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


我正在寻找的函数应该 return 像这样的字典:

{'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},
 }


我尝试创建一个递归函数如下:

@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


它似乎不起作用(它没有 return 预期的输出,字典在第一个 True 值处停止),我找不到原因(请不要对我太苛刻)。
任何人都可以通过显示我正在犯的错误以及如何解决它来帮助我吗?
请注意字典的深度不是先验的,所以我认为该方法应该是递归的(或迭代的)。

因为对于字典,1个键只能有1个值。您不能将多个 children 分配给 1 个 parent 键。

你的代码在这里

for child in child_parent_ids:
    tree_dict[self] = child.get_tree_dict()

将从同一个 parent 覆盖之前的 child。最后你有 1 parent 键只有一个 child.

也许你可以考虑使用列表来帮助形成树结构,而不仅仅是字典。然后,您可以向列表追加尽可能多的 children。

类似的东西(因为没有最小的工作示例,不知道你的代码究竟是如何工作的,不能保证工作,把它当作一个想法):

expected_dict = 
{'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-4': True}
  ]
}

def get_tree_dict(self):
    tree_dict = {}
    if self.child_parent_ids:
        tree_dict[self] = []
        for child in child_parent_ids:
            tree_dict[self].append(child.get_tree_dict())
        return tree_dict
    else:
        tree_dict[self] = True
        return tree_dict