Django - 打印所有对象的属性值

Django - print all objects attribute values

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>

views.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

models.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' 作为 string, 因此它使我们能够生成字符串并查询任意属性)。

因此,对于 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>

在您的上下文中包括:

context['wellinfo'] = [(field.name, field.value_to_string(self)) for field in Well_Info._meta.fields]

然后您可以在模板中循环遍历它,例如:

{% for name, value in wellinfo.get_fields %}
{{ name }} {{ value }}
{% endfor %}