【问题标题】:Django template table with missing data for some columns某些列缺少数据的 Django 模板表
【发布时间】:2020-11-10 04:02:32
【问题描述】:

好吧,我放弃了。我搜索了一遍又一遍,丢失了一些看起来像答案的东西,所以我不得不问。

比如说,一个区域电网的数据和每个发电厂都有一个一天的生产计划,所有这些数据都以 dicts 列表的形式出现,每个小时都有一个计划。数据还包括功耗预测,自然只有未来几个小时的数据。

[
 {'station_id':'Grid','plan_code':1000,'plan':{1:300,2:500,3:250,...,23:519,24:200}}
 {'station_id':'Plant1','plan_code':1001,'plan':{1:100,2:224,3:150,...,23:239,24:100}}
 {'station_id':'Plant2','plan_code':724,'plan':{1:200,2:226,3:100,...,23:240,24:100}} #every hour contains value
 {'station_id':'Consumption','plan_code':2003,'plan':{21:1600,22:1710,23:1250,24:1100}} #only few hours have data
] 

我试图用 Django 模板生成的是一张电网生产、消耗和平衡值的表格:

<table>
    <thead>
        <tr style="font-size: small">
            <th>Plan for</th>
            <th>Type</th>
            <th>01</th>
            <th>02</th>
            <th>03</th>
            ...
            <th>22</th>
            <th>23</th>
            <th>24</th>
        </tr>
    </thead>
    <tbody>
    {% for plan in plans %}
        <tr style="font-size: small">
            <td>{{ plan.station_id }}</td>
            <td>{{ plan.plan_code }}</td>
            {% for hour,val in plan.plan %}
               <td>{{ val }}</td>
            {%endfor%}
        </tr>
        {% endfor %}
    </tbody>
</table>

问题是:

  1. 如何确定计划的显示顺序?
  2. 如果没有提供该小时的值,我如何用空单元格填充消费计划行?

请在这里帮助初学者。

【问题讨论】:

  • 你想以什么顺序显示它们?你也可以发布你的views.py和models.py吗?

标签: python django templates


【解决方案1】:

想通了。

如果您的表格中缺少需要添加的单元格并且您还没有使用 pandas,您可以使用带有 None 值的键来完成字典。

    hours = range(1,25)

    for ob in a:
        for plan in a[ob]['plans']:
            if len(a[ob]['plans'][plan]) < 24:
                for h in hours:
                   a[ob]['plans'][plan][h] = a[ob]['plans'][plan].get(h)
                a[ob]['plans'][plan] = dict(sorted( a[ob]['plans'][plan].items()))

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-14
    相关资源
    最近更新 更多