html中的树结构与动态内容

问题描述 投票:0回答:1

我有来自数据库的数据作为查询执行的以下格式

[(‘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 
javascript python html django treeview
1个回答
0
投票

请尝试以下方法:

数据解析器:

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 %}
© www.soinside.com 2019 - 2024. All rights reserved.