【问题标题】:SQLAlchemy & Flask - Getting Results from Multi-Table querySQLAlchemy & Flask - 从多表查询中获取结果
【发布时间】:2020-05-06 18:26:35
【问题描述】:

试图找到不需要添加许多条件和额外代码的解决方案,并且无法在网上找到任何满足我特定需求的资源。

我有一个 Web 应用程序,它最终将成为一个简单的论坛和博客站点。将有个人用户和帐户,每个用户都可以成为朋友或关注其他用户。这样做的目的是,当您加好友和/或关注用户时,他们发布的任何状态更新都会显示在您的主屏幕上。

但是,代码仅显示您既是朋友又关注的人的状态,而不是如果您只是关注而不是朋友,反之亦然。返回结果的函数如下 -

    def related_posts(self):
    shown_posts = db.session.query(Status).join(followers, followers.c.followed_id == Status.user_id).join(
        friends, friends.c.friend_id == Status.user_id).filter(
        followers.c.follower_id == self.id, friends.c.user_id == self.id)
    own_posts = Status.query.filter_by(user_id=self.id)
    return own_posts.union(shown_posts).order_by(Status.timestamp.desc())

此代码是创建用户表的用户类的一部分。此代码引用另一个保存用户发布的状态的类,以及为促进朋友和关注功能的多对多关系而创建的两个子表。

返回的结果如下图所示-

@bp.route('/', methods=['GET', 'POST'])
@bp.route('/index', methods=['GET', 'POST'])
def index():
    form = StatusForm()
    # if request.method == 'POST' and form.submit():
    if form.validate_on_submit():
        status = Status(body=form.status.data, author=current_user)
        db.session.add(status)
        db.session.commit()
        flash('Your status has been updated!')
        return redirect(url_for('main.index'))
    user_status = Status.query.filter_by(user_id=current_user.id).order_by(Status.timestamp.desc()) if current_user.is_authenticated \
        else Status.query.order_by(Status.timestamp.desc())
    shown_posts = current_user.related_posts() if current_user.is_authenticated \
        else None
    return render_template('main/index.html', title='Welcome to the Blog!', form=form,
                           user_status=user_status, shown_posts=shown_posts)

我不知道是否有一种简单的方法可以做到这一点,我只是想念它,但我已经阅读了文档并在线搜索了该问题的解决方案。但是到目前为止我发现的还没有解决这个问题。非常感谢任何帮助,我希望我在这里提供了足够的信息以允许这样做。

【问题讨论】:

  • 为什么不将showed_posts 拆分为showed_posts_friends 和showed_posts_follower?将shown_posts 的查询拆分为两部分,并在返回中使用3 而不是2 的联合。在您当前的版本中,您将结果限制为朋友和关注者用户的状态。
  • 嗨,安迪,我知道这回复很晚,但非常感谢您的意见。我确实最终这样做了!可能是最明智的方法,因为它是最简单的方法,但由于某种原因暂时无法找到答案。

标签: python flask sqlalchemy


【解决方案1】:

这是一个很晚才结束的问题,但我收到了来自 Andi Schroff 的一个很好的回答作为对该问题的评论:

为什么不将showed_posts 拆分为showed_posts_friends 和showed_posts_follower?将shown_posts 的查询拆分为两部分,并在返回中使用3 而不是2 的并集。在您当前的版本中,您将结果限制为朋友和关注者的用户状态。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-29
    • 1970-01-01
    • 1970-01-01
    • 2017-05-29
    相关资源
    最近更新 更多