从模型对象中使用python在json中创建树

时间:2018-09-26 20:17:55

标签: python django python-3.x

我有一个存储模型,我需要从该模型中获取树状对象并像这样进行操作:

if model == 'Storage':
    if method == 'Read':
        try:
            list_sr = []
            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)
            print('Look' + str(jsonFormat))
            ...

输出字典数据,结果显示为以下形式:

{
    "children": [
        {
            "expanded": true,
            "id": "9",
            "text": "Title 1"
        },
        {
            "children": [
                "{'text:Test 1, leaf = True'}"
            ]
        },
        {
            "children": [
                "{'text:Test 2, leaf = True'}"
            ]
        },
        {
            "expanded": true,
            "id": "12",
            "text": "Title 2"
        },
        {
            "children": [
                "{'text:Test 3, leaf = True'}"
            ]
        },
        {
            "children": [
                "{'text:Test 4, leaf = True'}"
            ]
        }
    ],
    "expanded": "true",
    "text": "Storage"
}

我需要使用以下形式的数据:

expanded: true, text: "Storage",

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
    }

    ]
 }

 ]

在python中,我是新手,因此无法在循环中生成正确的数据,因此它们具有适合Ext.data.TreeStore的表示形式。如何在循环中更改代码以获取正确格式的数据?

0 个答案:

没有答案