SQLAlchemy left join using subquery

后端 未结 1 912
名媛妹妹
名媛妹妹 2021-02-10 21:45

Lets say there\'s a table \"posts\" which contains blog posts, and another table \"favorites\" which links a username to a post. Many users can favorite a post, so the relations

1条回答
  •  误落风尘
    2021-02-10 22:19

    Really you just need to replace the outerjoin with join, and the filter would work just fine.

    Also, if your favorites table contains no additional information and only links users and posts, you should consider simply defining a `Many to Many' relationship. In the documentation examples Parent/Child would be your User/Post.

    Update-1: just to answer second part of the question given your comment, the query below should give you an idea:

    current_user = 2
    subq = (db.session.query(favorites)
            .filter(favorites.user_id == current_user).subquery('ff'))
    q = (db.session.query(posts, subq.c.score)
         .outerjoin(subq, subq.c.post_id == posts.post_id))
    q = q.order_by(subq.c.score.desc())
    for post, score in q:
        print(post, score)
    

    0 讨论(0)
提交回复
热议问题