我正在使用MVC模型(django)。我在模板中有一个for循环,用于从sqlite3数据库收集数据。我需要填充一个JavaScript变量(使用JSON格式)从数据库中分割radar.client
字段。此字段是逗号分隔值字符串。我需要在不同的“子”值中将其解析为json。现在让我进入练习。
生成json var的代码如下所示:
var json = {
"id": "1",
"name": "Server",
"children": [
{% if clave_radar % }
{% for radar in clave_radar % }
{"id": "{{ radar.key }}",
"name": "{{ radar.ap }}",
"data": {"": "", "": ""},
"children": [
//This is where I need to split in different children
{"id": "1_{{ radar.key }}",
"name": "{{ radar.clients }}",
"data": {"": "", "": ""},
"children": []},
]},
{% endfor % }
{% endif % }
],
};
现在让我向您展示一个示例,说明服务器中处理过的代码如何为客户端显示:
var json_test={
"id": "1",
"name": "Server",
"children": [
{
"id": "13",
"name": "WLT",
"data": {"": "","": ""},
"children": [
{
"id": "1_13",
"name": "081196(Intel Corporate), 68a3c4(Liteon Technology Corporation), b8d9ce(Samsung Electronics)",
"data": {"": "","": ""},
"children": []
},
//Children Liteon and Samsung should appear here and not packed in 1_13
]
},
],
};
这就是我努力让它看起来像:
varjson_real={
"id": "1",
"name": "Server",
"children": [
{
"id": "13",
"name": "WLT",
"data": {"": "","": ""},
"children": [
{
"id": "1_13",
"name": "081196(Intel Corporate)",
"data": {"": "","": ""},
"children": []
},
{
"id": "2_13",
"name": "68a3c4(Liteon Technology Corporation)",
"data": {
"": "",
"": ""
},
"children": []
},
{
"id": "3_13",
"name": "b8d9ce(Samsung Electronics)",
"data": {"": "","": ""},
"children": []
},
]
},
]
};
答案 0 :(得分:3)
为什么不循环客户端,如下所示:
var json = {
"id": "1",
"name": "Server",
"children": [
{% if clave_radar % }
{% for radar in clave_radar % }
{"id": "{{ radar.key }}",
"name": "{{ radar.ap }}",
"data": {"": "", "": ""},
"children": [
{% for client in radar.clients %}
{"id": "1_{{ radar.key }}",
"name": "{{ client }}",
"data": {"": "", "": ""},
"children": []},
{% endfor % }
]},
{% endfor % }
{% endif % }
],
};
答案 1 :(得分:0)
我刚刚找到了解决这个问题的方法。首先,我受this how to split a string to an array with django
的启发我将此功能添加到radar
模型中:
def list_clients(self):
return self.clientes_encontrados.split('), ')
然后,代码想要像:
var json_radar = {
"id": "1",
"name": "Server",
"children": [
{% if clave_radar %}
{% for radar in clave_radar %}
{"id": "{{ radar.key }}",
"name": "{{ radar.ap }}",
"data": {"": "","": ""},
"children": [
{% if radar.clients != "null" %}
{% for client in radar.list_clients %}
{"id": "1_{{ radar.key }}",
"name": "{{ client }}",
"data": {"": "", "": ""},
"children": []},
{% endfor %}
{% endif %}
]},
{% endfor %}
{% endif %}
],
};