Ребят, помогите, пож-та, мне необходимо написать на python алгоритм построения дерева, результат буду формировать в json .
Модель в бд у меня выглядит так:
+–+————-+——–+
|id |name |parentid|
+–+————-+——–+
|9 |Title 1 |0 |
|10 |Test 1 |9 |
|11 |Test 2 |9 |
|12 |Title 2 |0 |
|13 |Test 3 |12 |
|14 |Test 4 |12 |
+–+————-+——–+
На выходе должен получить следующий вид:
children:[
{
text: "Title 1", id: '9', expanded: true,
children: [
{
text: "Test 1", leaf: true ,
},
{
text: "Test 2", leaf: true
}
]
},
{
text: "Title 2", id: '12', expanded: true,
children: [
{
text: "Test 3", leaf: true ,
},
{
text: "Test 4", leaf: true
}
]
}
]
storage = Storage.objects.all() for item_sr in list(storage): dict_sr = {} if item_sr.id_parent_id == 0: dict_sr['text'] = item_sr.name dict_sr['id'] = str(item_sr.id) dict_sr['expanded'] = True if item_sr.id_parent_id != 0: dict_sr['children'] = [{'text:' + item_sr.name + ", leaf = True"}] list_sr.append(dict_sr) result = {'expanded': 'true', 'text': 'Storage', 'children': list_sr} jsonFormat = json.dumps(result, indent=4, sort_keys=True, default=str)
Но правильный формат не получается. Помогите правильно написать код