django - Django - 打印所有对象属性值
问题描述
HTML
<thead>
<tr>
{% for field in fields %}
<th>{{ field }}</th>
{% endfor %}
</tr>
</thead>
<tbody>
{% for well in well_info %}
<tr>
<td><p>{{ well.api }}</p></td>
<td><p>{{ well.well_name }}</p></td>
<td><p>{{ well.status }}</p></td>
<td><p>{{ well.phase }}</p></td>
<td><p>{{ well.region }}</p></td>
<td><p>{{ well.start_date }}</p></td>
<td><p>{{ well.last_updates }}</p></td>
</tr>
{% endfor %}
<tr>
视图.py
class WellList_ListView(ListView):
template_name = 'well_list.html'
context_object_name = 'well_info'
model = models.WellInfo
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['fields'] = [field.name for field in models.WellInfo._meta.get_fields()]
return context
模型.py
from django.db import models
from django.urls import reverse
# Create your models here.
class WellInfo(models.Model):
api = models.CharField(max_length=100, primary_key=True)
well_name = models.CharField(max_length=100)
status = models.CharField(max_length=100)
phase = models.CharField(max_length=100)
region = models.CharField(max_length=100)
start_date = models.CharField(max_length=100)
last_updates = models.CharField(max_length=100)
def get_absolute_url(self):
return reverse("")
def __str__(self):
return self.well_name
我能够通过获取上下文 ['fields'] 列出所有属性字段名称,但我不知道如何自动打印每个对象的所有属性值。
因此,在我的 html 文件中,我对所有属性名称进行了硬编码,但我想知道是否可以通过使用 for 循环以更优雅的方式实现这一点。所以像:
<tbody>
{% for well in well_info %}
<tr>
{% for value in attribute_list %}
<td><p>{{ well.value }}</p></td>
{% endfor %}
</tr>
{% endfor %}
<tr>
解决方案
使用getattr
,您可以构建一个值列表,例如:
fields = context['fields']
context['well_info'] = [
[getattr(o, field) for field in fields ]
for instance in context['well_info']
]
如果你写getattr(x, 'y')
这相当于x.y
(请注意,因为getattr(..)
我们'y'
用作字符串,所以它使我们能够生成字符串并查询任意属性)。
对于old well_info
中的每个实例,我们因此将其替换为包含每个字段相关数据的子列表。
请注意,这里的well_info
属性不再是模型实例的可迭代对象,而是列表的列表。如果您想同时访问两者,最好将其存储在上下文中的另一个键下。
然后你可以像这样渲染它:
<thead>
<tr>
{% for field in fields %}
<th>{{ field }}</th>
{% endfor %}
</tr>
</thead>
<tbody>
{% for well in well_info %}
<tr>
{% for value in well %}
<td>{{ value }}</td>
{% endfor %}
</tr>
{% endfor %}
<tr>
</tbody>
推荐阅读
- php - smarty php中的函数在哪里设置?
- rest - Firebase REST orderby自动生成ID的嵌套子项?
- mysql - android firebase手机身份验证我们可以使用firebase for otp存储在mysql数据库中吗
- javascript - JS:使用 setInterval 有条件地播放声音
- html - 离子
之间 和 没有出现 - python - python matplotlib在axes.lines上迭代得到错误的长度
- php - 面对 CakePHP 和 HTML2PDF 的问题
- c++ - 带有-O选项的g ++浮点行为不是严格的C ++ 11标准保形?
- javascript - Vue2从循环组件中的子调用父方法
- vb.net - 从 datagridview 传递空单元格值