python - 为什么这个页面只显示一个帖子?
问题描述
所以这是我收藏页面的代码:
@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 评论中意识到这一点
更新:
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)
推荐阅读
- angular - 我不能在 AppRoutingModule 中使用 TranslateService 吗?
- c++ - 线程 4:EXC_BAD_ACCESS(代码=1,地址=0x0)
- django - 使用 Docker 在 Heroku 上设置和部署 Cookiecutter-Django 项目:部署失败,应用程序尚未加载
- database - 需要缩小出现在子表单中的查询结果,然后选择并显示平均值
- c++ - 有没有一种通用的方法来“取消保护”静态 const 成员?
- c# - 在 AssemblyInfo.cs 中使用更新的值
- c# - 为什么我不能正确设置易失性注册表值?
- android - 从recyclerview适配器内的arraylist中删除元素,OnBindViewHolder方法内的NotifyDatasetChanged
- apache - 特定文件夹的虚拟主机不是整个域?
- python - 删除列表字典中的元素