Flask-sqlalchemy多对多查询的问题?

在看flask web开发这本书的时候,在讲到多对多的时候,有一个地方是显示用户所关注的所有用户的文章和自己的文章,文是的方法是添加自关注,我想直接在sqls查询的时候加上他自己的ID。但是最后查出来分页的时候出了问题。

@main.route('/test', methods=['GET', 'POST'])
def test():
    form = PostForm()
    if current_user.can(Permission.WRITE_ARTICLES) and form.validate_on_submit():
        post = Post(body=form.body.data, author=current_user._get_current_object())
        db.session.add(post)
        return redirect(url_for('.index'))
    page = request.args.get('page', 1, type=int)
    show_followed = False
    if current_user.is_authenticated:
        show_followed = bool(request.cookies.get('show_followed', ''))
    if show_followed:
        query = current_user.followed_posts
    else:
        query = Post.query
    print(query.order_by(Post.timestamp.desc()).paginate(1, 5, error_out=False).total)
    print(query.order_by(Post.author_id).paginate(1, 5, error_out=False).total)

    pagination = query.order_by(Post.author_id).paginate(1, 5).items


    return render_template('test/test.html', posts=pagination)

如上, 我查询出文章之后做了分页,print分别打印出了按时间倒序分页和按文章用户ID分页,但现在问题是按时间分页的时候显示只有一条数据,按用户ID分页时显示正常。上面的query对应的是用户models的一个属性,进行多对多查询。麻烦各位给看看问题出在哪里?

    @property
    def followed_posts(self):
        return Post.query.join(Follow, Follow.followed_id == Post.author_id).filter(or_(Follow.follower_id == self.id, Post.author_id == self.id))

将分页对应的sql语句打印出来也没发现有什么问题

SELECT posts.id AS posts_id, posts.body AS posts_body, posts.body_html AS posts_body_html, posts.timestamp AS posts_timestamp, posts.author_id AS posts_author_id 
FROM posts JOIN follows ON follows.followed_id = posts.author_id 
WHERE follows.follower_id = ? OR posts.author_id = ? ORDER BY posts.timestamp DESC
阅读 3k
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题