【问题标题】:Is there a way to concatenate a django object query from a template?有没有办法从模板连接 django 对象查询?
【发布时间】:2020-07-29 12:00:45
【问题描述】:

我有以下代码:

<table id="MyTable" class="highlight responsive-table" >
    <thead>
      <tr>
          {% with columns as columns %}
              {% for columns in columns %}
                <th class="th-sm">{{ columns }}</th>
              {% endfor %}
          {% endwith %}

      </tr>
    </thead>
    <tbody>
    {% for trans in transactions %}
      <tr>
          <td> {{ trans.transactionsequencenumber }}</td>
          <td> {{ trans.posid }}</td>
          <td> {{ trans.transactionnumber }}</td>
      </tr>

    {% endfor %}


  </table>

它适用于显示静态表数据,但想法是通过用户偏好模型设置被迭代的列,因此表列可以根据用户进行更改,可能有 90 多个列可供选择,这就是我的问题所在。

下面的伪代码有助于说明我的目标:

<table id="MyTable" class="highlight responsive-table" >
<thead>
  <tr>
      {% with columns as columns %}
          {% for columns in columns %}
            <th class="th-sm">{{ columns }}</th>
          {% endfor %}
      {% endwith %}

  </tr>
</thead>
<tbody>
{% for trans in transactions %}
  <tr>
      <td> {{ trans.{{columns}} }}</td>
  </tr>

{% endfor %}

到目前为止,我已经尝试过简单的字符串连接,但这只是将字符串打印到表中,而不是对象数据,

我们将不胜感激任何帮助和/或指导。 请客气,这是我的第一个问题。

【问题讨论】:

  • 你能想出除columns之外的另一个名字吗?我只是觉得两次使用同一个名字并不安全。
  • 我知道这不是最好的生产方式,但我现在只是在做原型,所以它会改变

标签: python django django-models django-templates


【解决方案1】:

对于在数据库属性中代表一行的每个对象,您将其放入一列中。例如:

<tr>
  <th> title </th>
  <th> body </th>
</tr>

{% for post in posts %}
  <tr>
    <td> {{post.title}}</td>
      <td> {{post.body}} </td>
        
  </tr>  
{% endfor %}

【讨论】:

    猜你喜欢
    • 2018-09-19
    • 2014-02-06
    • 1970-01-01
    • 1970-01-01
    • 2022-01-05
    • 2012-08-21
    • 1970-01-01
    • 2021-01-27
    • 1970-01-01
    相关资源
    最近更新 更多