【问题标题】:Django - template containing model's 'table'Django - 包含模型“表”的模板
【发布时间】:2017-12-04 23:43:33
【问题描述】:

这是我的问题: 我想在模板中打印一个表格,其中包含每个字段的每个对象

这是我的解决方案:

views.py

def start(request):
  all_rows = Person.objects.all()
  all_fields_names = Person._meta.get_fields()
  content = { 'all_rows': all_rows, 
              'all_fields_names': all_fields_names }

  return render(request, 'start.html', content)

start.html

<table class="table table-striped table-hover table-responsive">
<thead>
  {% for names in all_fields_names %}<th>{{ names.name |title }}</th>{% endfor %}
</thead>
<tbody>
  {% for row in all_rows %}
    <tr>
      <td>{{ row.name }}</td>
      <td>{{ row.yabadiba }}</td>
      <td>{{ row.value1 }}</td>
      <td>{{ row.value2 }}</td>
    </tr>
  {% endfor %}
</tbody>
</table>

一切都很完美。问题是,当我不知道类中有多少字段时。其次,我的解决方案打破了 DRY 规则。我试过了:

getattr(行,名称)

和嵌套循环,没有成功。 有没有简单的解决方案?

此外:如何为每个班级打印这样的视图?

【问题讨论】:

    标签: python django


    【解决方案1】:

    您需要的是views 中的values_list 查询,它在迭代时返回元组。每个元组包含来自各个字段或表达式的值,传入values_list()

    all_fields_names = Mileage._meta.get_fields()   
    value_fields = [f.name for f in all_fields_names]
    all_rows = Mileage.objects.values_list(*(value_fields)) #pass fields to value_list
    

    然后你可以在templates 中使用嵌套的for循环:

    {% for row in all_rows %}
        <tr>{% for value in row %}<td>{{ value }}</td>{% endfor %}</tr>
    {% endfor %}
    

    【讨论】:

      猜你喜欢
      • 2012-03-16
      • 1970-01-01
      • 2013-08-27
      • 1970-01-01
      • 2014-05-13
      • 2011-07-12
      • 2011-01-07
      • 2013-12-16
      • 1970-01-01
      相关资源
      最近更新 更多