【问题标题】:How to get current post id when writing raw sql query in Flask SQL Alchemy?在 Flask SQLAlchemy 中编写原始 sql 查询时如何获取当前的帖子 ID?
【发布时间】:2020-04-28 16:05:19
【问题描述】:

我编写了一个原始 SQL 查询来显示点赞帖子的用户列表,但查询返回的用户列表不仅喜欢当前帖子,还喜欢其他帖子。

这是我写的路线

@app.route('/like/<int:post_id>/viewLikes')
@login_required
def viewLikers(post_id):
    post = Post.query.get_or_404(post_id)
    result = db.engine.execute("Select username from user, PostLike, Post where user.id=PostLike.users_id and PostLike.post_id=post.id")
    return render_template('viewLikes.html', likers=result)

【问题讨论】:

    标签: python sql flask flask-sqlalchemy


    【解决方案1】:

    尝试在查询中再添加一个条件:

    post = Post.query.get_or_404(post_id)
    sql = "Select username from user, PostLike, Post where user.id=PostLike.users_id and PostLike.post_id=post.id and PostLike.post_id = :pid"
    result = db.engine.execute(sql, {'pid': post} )
    
    

    【讨论】:

    • 乐于助人:)
    猜你喜欢
    • 1970-01-01
    • 2011-06-04
    • 2011-06-21
    • 1970-01-01
    • 2017-04-26
    • 1970-01-01
    • 2021-12-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多