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
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)