Django-打印所有对象属性值

时间:2018-07-19 19:22:16

标签: django django-models django-templates django-views django-context

HTML

<?php

namespace App\Models;

interface Auditable {
    public function getAuditDescription();
    public function needAudit();
}

views.py

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

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

我能够通过获取context ['fields']来列出所有属性字段名称,但是我不知道如何自动打印每个对象的所有属性值。

因此,在我的html文件中,我对所有属性名称进行了硬编码,但我想知道是否可以通过使用for循环以更优雅的方式实现此目的。像这样:

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

2 个答案:

答案 0 :(得分:2)

根据您的情况,包括:

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 %}

答案 1 :(得分:1)

使用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>
相关问题