home = [
{"id": 1, "name": "食品", "parent_id": 0},
{"id": 2, "name": "手机", "parent_id": 0}
]
category_list = [
{"id": 1, "name": "食品", "parent_id": 0},
{"id": 2, "name": "手机", "parent_id": 0},
{"id": 3, "name": "华为", "parent_id": 2},
{"id": 4, "name": "小米", "parent_id": 2},
{"id": 5, "name": "华为P系列", "parent_id": 3},
{"id": 6, "name": "生食", "parent_id": 1},
{"id": 7, "name": "熟食", "parent_id": 1},
{"id": 8, "name": "华为Mate系列", "parent_id": 3},
]
res = []
def get_subcategory(sub_category, one_res):
for one in range(len(sub_category)):
if one == 0:
one_res["children"] = sub_category
item_child_list = []
for item_child in category_list:
if item_child["parent_id"] == sub_category[one]["id"]:
item_child_list.append(item_child)
a = get_subcategory(item_child_list, one_res["children"][one])
return one_res
for item in home:
item_child_list = []
# 获取第二层
for item_child in category_list:
if item["id"] == item_child["parent_id"]:
item_child_list.append(item_child)
resp = get_subcategory(item_child_list, item)
res.append(resp)
print(res)
"""
食品
生食
熟食
手机
华为
华为P系列
华为Mate系列
小米
[{'id': 1, 'name': '食品', 'parent_id': 0, 'children': [{'id': 6, 'name': '生食', 'parent_id': 1}, {'id': 7, 'name': '熟食', 'parent_id': 1}]}, {'id': 2, 'name': '手机', 'parent_id': 0, 'children': [{'id': 3, 'name': '华为', 'parent_id': 2, 'children': [{'id': 5, 'name': '华为P系列', 'parent_id': 3}, {'id': 8, 'name': '华为Mate系列', 'parent_id': 3}]}, {'id': 4, 'name': '小米', 'parent_id': 2}]}]
"""