Python 为什么这个页面只显示一篇文章?
这是我的收藏夹页面代码:Python 为什么这个页面只显示一篇文章?,python,flask,jinja2,Python,Flask,Jinja2,这是我的收藏夹页面代码: @app.route('/favorites') @login_required def favorites(): cur=mysql.connection.cursor() r = cur.execute("SELECT post_id FROM favorites WHERE username = %s",[session['username']]) if r==0: msg='No favorites Found'
@app.route('/favorites')
@login_required
def favorites():
cur=mysql.connection.cursor()
r = cur.execute("SELECT post_id FROM favorites WHERE username = %s",[session['username']])
if r==0:
msg='No favorites Found'
return render_template('favoritest.html',msg=msg)
else:
data=cur.fetchall()
for row in data:
pos_id = row["post_id"]
cur.execute("SELECT* FROM posts WHERE id=%s ORDER BY created_at DESC",[pos_id])
naa=cur.fetchall()
cur.close()
return render_template("favoritest.html",naa = naa)
这是我的模板:
{% block body %}
{% for itm in naa %}
<tr>
<td><a href="posts/{{itm['id']}}/{{itm['title']}}">{{itm['title']}}</a></td></tr>
{% endfor %}
{% endblock %}
它只显示一个帖子,即使有多个帖子,那么这里有什么问题,如何解决
谢谢你在这段话里
for row in data:
pos_id = row["post_id"]
cur.execute("SELECT* FROM posts WHERE id=%s ORDER BY created_at DESC",[pos_id])
您只运行一次数据库查询。因此,您应该将其包括在for循环中,如下所示:
for row in data:
pos_id = row["post_id"]
cur.execute("SELECT* FROM posts WHERE id=%s ORDER BY created_at DESC",[pos_id])
从@Matthias评论中意识到了这一点
更新:
您只获取最后一个pos_id的数据。@Matthias那么如何获取所有pos_id呢?@lawlawi,您能否显示此查询的输出SELECT*FROM POST,其中id=%s ORDER BY created_at DESC,如果用示例post\u id替换%s?我怀疑它只返回一行,因此您需要将结果附加到列表并返回itI我不明白您的意思,但pos\u id的输出只是一个结果:10一个post的id如何附加结果并返回它?现在我们有了一个解决方案。
naa = []
for row in data:
pos_id = row["post_id"]
cur.execute("SELECT* FROM posts WHERE id=%s ORDER BY created_at DESC",[pos_id])
naa.append(cur.fetchall())
cur.close()
return render_template("favoritest.html",naa = naa)