我有一个包含深层嵌套子项的数据库模型。我试图添加所有底层ID(所有级别)添加到字典条目。我目前的代码如下:
children = obj.children
for child in children:
data["children_ids"].append(child.id)
for child in child.children:
data["children_ids"].append(child.id)
for child in child.children:
data["children_ids"].append(child.id)
for child in child.children:
data["children_ids"].append(child.id)
此代码功能齐全,但问题相当明显。我不想一遍又一遍地编写相同的代码:它很丑陋,不切实际且不易维护。我该怎么做?
答案 0 :(得分:5)
while循环怎么样?
children = list(obj.children)
while children:
child = children.pop()
data["children_ids"].append(child.id)
grandchildren = getattr(child, 'children', None)
if grandchildren:
children.extend(list(grandchildren))
答案 1 :(得分:5)
使用递归函数在不同的子代上运行相同的代码:
def add_children_ids(ids, children):
for child in children:
ids.append(child.id)
add_children_ids(ids, child.children)
children = obj.children
data['children_ids'] = []
add_children_ids(data['children_ids'], children)
因为ids
是一个可变列表,所以不需要return