【发布时间】:2019-05-11 22:06:32
【问题描述】:
我更改了查询数据库的方式,虽然结果加载正常,但我无法让信息显示在模板中。
我尝试以更简单的方式重写代码以尝试捕获错误,但一无所获。我不知道还能做什么。
from flask import render_template
from app import app, db
@app.route("/page")
def page():
'''
this is the old way that is useable in the template
result = Test.query.filter_by(id=12))
'''
# test variables
d = 65465
s = 'rebrb'
result = db.engine.execute('SELECT * FROM test WHERE id IN (183, 184, 180, 181, 182, 185, 95, 179)')
# new way works here but not in the template
print(result)
for row in result:
print(row.content)
return render_template('page.html', s=s, d=d, result=result, title='Video')
'''
The d and s load but the for loop doesn't do anything
'''
{{ d }}
{{ s }}
{% for row in result %}
{{ row }}
{{ d }}
{% endfor %}
d 和 s 变量显示出来,但在 for 循环之后没有任何效果。
编辑 1:我通过在将结果发送到模板之前将结果转换为列表取得了一些进展,但我觉得我不应该这样做,我仍在寻找更好的选择。
编辑 2:我发现我也可以通过这种方式进行查询。
result = Test.query.filter(Test.id.in_(183, 184, 180, 181, 182, 185, 95, 179))
哪个效果更好,但我需要结果与列表的顺序相同
【问题讨论】:
-
您是否在模板中尝试过
{{ row.content }}而不仅仅是{{ row }}?自从我使用原始 SQL 以来已经有一段时间了 - 我更喜欢 SQLAlchemy,这就是我现在使用的,所以我不记得 SQL 查询返回什么样的数据结构 - 但假设你可以打印 row.content在 python 中,您应该能够在模板中获取 row.content ...“应该”是有效词... -
@Steve 一段时间后我发现您可以使用 sqlalcemy 执行相同的查询,并且现在可以使用。
-
@Steve 实际上我发现了另一个问题,我需要结果中的行 ID 与它们在列表中的顺序相同。你知道如何用 sqlalchemy 做到这一点吗?
-
如果您使用 Flask-SQLAlchemy,您可以使用 order_by 方法按特定列对结果进行排序。结果 = Test.query.filter(Test.id.in_(95, 179, 180, 181, 182, 183, 184, 185)).order_by(Test.id).all()
-
我需要按以下顺序显示结果:(183, 184, 180, 181, 182, 185, 95, 179),我在这里找到了方法。 stackoverflow.com/questions/29326297/…
标签: python database postgresql flask flask-sqlalchemy