繁体   English   中英

如何从 Django 模板中的字典迭代多个键

[英]How can I iterate multiple key from a dictionary in Django template

我已经在 django 中将视图中的数据提供给模板。我想迭代这些多个键来构建一个 html 表。

视图.py

data={'pacientes':p,'inicios':i,'finales':f,'enfermedad':enf} # p, i and f are lists
return render(request,'verEnf.html',data)

我想做类似的事情

index.html

 <table>
     {% for p, i, f in pacientes, inicios, finales %} # I know that this code is not work
        <tr>
            <td>{{ p.nombre }}</td>
            <td>{{ i }}</td>
            <td>{{ f }}</td>
        <tr>
     {% endfor %}
 </table>

p 是来自 Pacientes 的 object

class Usuario(models.Model):
    dni=models.CharField(max_length=9,primary_key=True)
    clave=models.CharField(max_length=16)
    nombre=models.CharField(max_length=30)
    ...

我是一个字符串列表

('20-2-2014', '12-2-2014', ..., '11-5-2014')

我想paciente,inicio和finales的每个索引之间都是相关的。

就像Ignacio所说的那样,您可以在视图中编写一些代码,然后再将其传递给模板以解决您的问题。 可能的解决方案是将值打包在这样的元组列表中:

[
  (pacientes[0], inicios[0], finales[0]),
  (pacientes[1], inicios[1], finales[1]),
  ...
]

您可以通过在视图中使用zip功能轻松实现此目的:

pacientes_data = zip(p, i, f)
data={'pacientes_data':pacientes_data,'enfermedad':enf} # p, i and f are lists
return render(request,'verEnf.html',data)

在您的模板中:

<table>
     {% for p,i,f in pacientes_data %}
        <tr>
            <td>{{ p.nombre }}</td>
            <td>{{ i }}</td>
            <td>{{ f }}</td>
        </tr>
     {% endfor %}
</table>

这是类似任务的工作解决方案:

 <table class="table"> <thead> <tr> <th scope="col">#</th> <th scope="col">Model Name</th> <th scope="col">Device Count</th> </tr> </thead> <tbody> {% for all_model in all_models %} <tr> <th scope="row">{{ forloop.counter }}</th> <td>{{ all_model.0 }}</td> <td>{{ all_model.1 }}</td> </tr> {% endfor %} </tbody> </table>

在视图.py

    all_models = []
    all_models_names = [1,2,3,4]
    all_models_names_values = [1,2,3,4]
    all_models = zip(all_models_names,all_models_names_values)
return render(request, "sample.html",{'all_models':all_models})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM