【问题标题】:How can you access an sqlalchemy table column using jinja with variable如何使用带有变量的 jinja 访问 sqlalchemy 表列
【发布时间】:2020-07-16 19:07:51
【问题描述】:

假设我使用 SQLAlchemy 创建了一个如下所示的表:

Table
+----+------+------+------+-----+
| id | Col1 | Col2 | Col3 | foo | ...
+----+------+------+------+-----+
|  1 |  a   |  b   |  c   | bar | ...
+----+------+------+------+-----+
   .
   .
   .

我正在使用 python flask 来渲染一个 html 模板。

假设我使用flask 的render_template 方法将此表的一行传递给我的html 模板。

return render_template('foo'.html, row=Table.query.filter_by(id=1).first())

然后在foo.html 中,我想遍历这一行并访问以col 开头的每一列的值。

换句话说,我只想访问a,b,c,而不是bar

我试过了:

{% for i in range(1,3) %}
  {{ row.coli }}   
{% endfor %}

但是这不起作用。

我怎样才能做到这一点?

【问题讨论】:

  • 您好,我尝试添加{{ getattr(row, 'col' + str(i)) }},但收到错误jinja2.exceptions.UndefinedError: 'str' is undefined。有什么想法吗?
  • 如果你知道这些列,你不妨直接使用它们,即写{{ row.Col1 }},然后写{{ row.Col2}},等等(如果使用Core,则写{{ row.c.Col1 }})。

标签: python html flask sqlalchemy flask-sqlalchemy


【解决方案1】:

你不能这样做,因为 col1,col2 不是数组,它们只是 sql 中的列名。

【讨论】:

  • 你能提供一个解决方案,因为这是不可能的
  • 我已经给出了解决方案。检查一下。
【解决方案2】:
row = Table.query.filter_by(id=1).first()
return render_template('foo.html', row=row)

在 HTML 中使用这个:

{{row.col1}} <!--Output : a -->
{{row.col2}} <!--Output : b -->
{{row.col3}} <!--Output : c -->

这会有所帮助。

【讨论】:

    【解决方案3】:

    除非我误解了你的意思,否则你可以这样做:

    {% for i in row %}
      {{ i.col1 }}{{ i.col2 }}{{ i.col3 }}   
    {% endfor %}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-29
      • 1970-01-01
      • 1970-01-01
      • 2017-06-20
      • 2023-01-21
      • 1970-01-01
      • 1970-01-01
      • 2016-04-26
      相关资源
      最近更新 更多