首页 > 解决方案 > 为什么这个页面只显示一个帖子?

问题描述

所以这是我收藏页面的代码:

@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 %}

即使有多个帖子,它也只显示一个帖子,那么这里有什么问题以及如何解决它?

谢谢

标签: pythonflaskjinja2

解决方案


在这个片段中,

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)

推荐阅读