首页 > 解决方案 > 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>

标签: djangodjango-modelsdjango-templatesdjango-viewsdjango-context

解决方案


使用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>

推荐阅读