这是我的“收藏夹”页面的代码:
@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 %}
即使有多个帖子,它也只显示一个帖子,那么这里有什么问题以及如何解决?
谢谢
答案 0 :(得分:1)
在此代码段中,
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评论实现了这一点
更新:
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)