首页 > 解决方案 > 在 Django 中渲染数据透视表

问题描述

我正在尝试渲染使用 django_pivot 制作的数据透视表。该表将贷款等级(A、B、C、D、E、F)作为行,将期限作为列(月数)和贷款金额的总和作为值。

视图.py:

from django_pivot.pivot import pivot
from django.db.models import Sum

def data(requests):


pivot_table = pivot(loan, 'grade', 'term', 'amount', aggregation=Sum)
print(pivot_table)

context = {
           "pivot_table": pivot_table,
            }

return render(requests, 'dashboard/data.html', context=context)

模型.py:

class loan(models.Model):
    loanid = models.CharField(max_length = 200, null=True)
    amount = models.IntegerField(null=True)
    term = models.IntegerField(null=True)
    interest = models.FloatField(null=True)
    borrower = models.CharField(max_length=200, null=True)
    grade = models.CharField(max_length = 200, null=True)
    status = models.CharField(max_length = 200, null=True)

    def __str__(self):
        return self.loanid

我被困在如何用 HTML 呈现这个表格。对于我的“正常”表,我使用正常的 jinja django 方式来呈现这样的表(请原谅我的凌乱缩进):

<div class="col-sm-8 grid-margin stretch-card">            
            <div class="card table-card" style="width: 105%">
              <table id="MyTable" class="table table-striped table-bordered mydatatable">
                  <thead>
                  <tr>
                      <th scope="col-sm">name</th>
                      <th scope="col-sm">email</th>
                      <th scope="col-sm">gender</th>
                      <th scope="col-sm">income</th>
                      <th scope="col-sm">yearsworked</th>
                      <th scope="col-sm">ficoscore</th>
                      <th scope="col-sm">dti</th>
                  </tr>
                  </thead>
                  {% for i in borrower_data %}
                  <tr>
                      <td>{{ i.name }}</td>
                      <td>{{ i.email }}</td>
                      <td>{{ i.gender }}</td>
                      <td>{{ i.income }}</td>
                      <td>{{ i.yearsworked }}</td>
                      <td>{{ i.ficoscore }}</td>
                      <td>{{ i.dti }}</td>
                  </tr>
                  {% endfor %}
                  </tbody>
              </table>
            </div>
        </div> 
      </div>
</div>

我不清楚如何使用数据透视表来呈现它,因为我的行和列现在都是动态的。这里提到了创建数据透视表https://pypi.org/project/django-pivot/,但是如何正确渲染它对我来说仍然是一个谜。任何帮助将不胜感激。

标签: pythondjangopivot

解决方案


推荐阅读