首页 > 解决方案 > 具有动态内容的 html 中的树结构

问题描述

我有来自数据库的数据,查询执行格式如下

[(‘Country-1’, ‘state1’), (‘Country-1’, ‘state2’), (‘Country-1’, ‘state3’),
(‘Country-2’, ‘state1’), (‘Country-2’, ‘state2’), (‘Country-2’, ‘state3’),
(‘Country-3’, ‘state1’), (‘Country-3’, ‘state2’), (‘Country-3’, ‘state3’)]

我想将此结果集转换为以下格式

context = { 
    'countries': [ { 'Countryname': 'country1’,
                    'state': [ {  'Statename': 'state1'},
                               {'Statename': 'state2'},
                               {'Statename': 'state3'} ]
                    },
                    { 'Countryname': 'country2’,
                    'state': [ {  'Statename': 'state1'},
                               {'Statename': 'state2'},
                               {'Statename': 'state3'} ]
                    }, 
                    { 'Countryname': 'country3’,
                    'state': [ {  'Statename': 'state1'},
                               {'Statename': 'state2'},
                               {'Statename': 'state3'} ]
                    }
                ]
}

这样我就可以在 Django 中迭代 HTML 中的数据以创建树格式:

<ul class = "myUL">
  {% for country in data %}
            <li class = "caret"> {{ country.countryname }} </li>
            <ul class="nested">
              {% for state in country.statename %}
                <li>{{state.statename}}</li>
                {% endfor %}
            </ul>
  {% endfor %}

HTML 的预期输出为:

   Country-1  
             State1
             State2
             State3 
   Country -2 
             State1
             State2
             State3 
   Country -3 
             State1
             State2
             State3 

标签: javascriptpythonhtmldjangotreeview

解决方案


尝试以下操作:

数据解析器:

data = [('Country-1', 'state1'), ('Country-1', 'state2'), ('Country-1', 'state3'), ('Country-2', 'state1'), ('Country-2', 'state2'), ('Country-2', 'state3'), ('Country-3', 'state1'), ('Country-3', 'state2'), ('Country-3', 'state3')]

reformatted_data = {}

for pair in data:

    state_list = reformatted_data.get(pair[0], None)

    if state_list:
        if pair[1] in state_list:
            pass
        else:
            reformatted_data[pair[0]].append(pair[1])
    else:
        reformatted_data[pair[0]] = [pair[1]]

# Try this print in your console to make sure it's working properly
print(reformatted_data)

显示数据的模板:

<ul class = "myUL">
  {% for country, statelist in data.items %}
            <li class = "caret"> {{ country }} </li>
            <ul class="nested">
              {% for state in statelist %}
                <li>{{ state }}</li>
                {% endfor %}
            </ul>
  {% endfor %}

推荐阅读