python - 从模型对象中使用 python 在 json 中创建树
问题描述
我有一个存储模型,我需要从中获取树形式的对象并这样做:
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 的表示。如何更改循环中的代码以获取正确格式的数据?
解决方案
推荐阅读
- paypal - Paypal - 自定义徽标出现在结帐页面上,但不在购物车页面上
- javascript - 只允许滚动在某些元素上停止
- node.js - Node.js“节点”命令不起作用,只是退出
- html - 与 HTML 表格相关的 tabOrder
- amazon-web-services - AWS Lambda Function with VPC only works when in Private Subnet
- spring-boot - Spring Cloud sleuth 不适用于 log4j2
- ios - Yubo 以前称为 Yello 是如何在重新安装后记住用户的?
- extjs - How to insert HTML inside an Ext.each() in the labeFormatter function of legend-EXTJS -highcharts
- java - Can we get two return types from getItemCount() in RecyclerView?
- javascript - Images not loading Webpack/Webpack-dev-serve