DJango表中的动态字典键

2024-10-02 22:33:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我对Django完全陌生,需要帮助。我有一个字典的动态列表,我想显示在django表中

[{'index': 'Price', 'Price': 1.0}, {'index': 'Sale', 'Price': 1.0}, {'index': 'Reviews', 'Price': -1.0}]

“索引”键将保持不变,但第二个键是动态的。我想在表格中显示这些数据。我可以显示第一个关键点的值,但不知道如何显示动态关键点的值

我的django模板代码如下

 <div class="container fluid">
            <table class="table table-striped">
                <h2 class="text-center">Correlation with {{var}}</u></h2><br>
                <thead>
                    <tr>
                        <th>Index</th>
                        <th>Score</th>
                        

                    </tr>
                    {% for var in variable %}
                    <tr>
                        <td>{{var.index}}</td>
                        <td>{{var.{{input}}</td>
                    </tr>
                    {% endfor %}
                </thead>
                </tbable>
        </div>

Views.py

def corelation(request):
    if request.method == "POST":
        var_input = request.POST.get('variable')
        data = {'Price':[23, 65], 'Sale':[76, 82], 'Reviews':[52, 34]}
        df = pd.dataframe(data)
        corr = df.corr()
        var_corr = corr[var_input].sort_values(ascending = False)

        
        #this is for showing item wise correlation() fucntion
        json_varCorr = var_corr.reset_index().to_json(orient ='records')
        data_varCorr = []
        data_varCorr = json.loads(json_varCorr)

        context = {'variable': data_varCorr,
                    'input':var_input,
        }
        
        return render(request, 'variable.html', context)

Tags: jsoninputdataindexrequestvar动态variable
2条回答

我想出来了

<div class="container fluid">
            <table class="table table-striped">
                <h2 class="text-center">Correlation with {{input}}</u></h2><br>
                <thead>
                    <tr>
                        <th>Index</th>
                        <th>Score</th>
                    
                    </tr>
                    {% for var in variable %}
                    <tr>
                    {% for key,val in var.items %}
                        <td>{{val}}</td>
                    {% endfor %}
                    </tr>
                    {% endfor %}
                    
                </thead>
                </tbable>
        </div>  

考虑到您的变量为:

variable = [{'index': 'Price', 'Price': 1.0}, {'index': 'Sale', 'Price': 1.0}, {'index': 'Reviews', 'Price': -1.0}]

要获取键及其值,可以在模板中执行以下操作:

{% for var in variable %}
  {% for key, val in var.items %}
    <p>{{key}} - {{val}}</p>
  {% endfor %}
{% endfor %}

相关问题 更多 >