【问题标题】:Django - How to retrieve columns in template automatically from a query in views.py?Django - 如何从views.py中的查询中自动检索模板中的列?
【发布时间】:2019-11-19 10:16:02
【问题描述】:

有一个包含 30 列的模块。 我在 views.py 中查询此表以获取最后一条记录(最后一行)。 要获取模板(index.html)中的数据,我必须写下每一列,并在它前面写下它的值。我必须做30次! 有没有类似 {{form}} 的东西可以自动或至少通过使用 {% for ... %} 来获取所有列及其值?

在views.py中

def articlesindex(request):    
    data = Articles.objects.all().last()
    return render(request, 'Articles\index.html', {'articles':data})

在 index.html 中

{{ articles }}   (does not work)
{{ articles.a_table }} (does not work)
 {% for k,v in articles %} (does not work)
        <tr>
            <td>{{ k }}</td>
            <td>{{ v }}</td>
        </tr>

{% endfor %}

【问题讨论】:

    标签: django django-templates django-views


    【解决方案1】:

    这是因为last() 在查询集中返回一个对象(请参阅文档here)。因此,由于它是单个对象,因此您将只有一行。您可以按如下方式渲染对象:

    <tr>
       <td>{{ articles.attr_1 }}</td>
       <td>{{ articles.attr_2 }}</td>
       ...
       <td>{{ articles.attr_n }}</td>
    </tr>
    

    属性一个一个

    【讨论】:

      猜你喜欢
      • 2018-02-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-09
      • 2020-09-20
      相关资源
      最近更新 更多