SimilarPost = aliased(Post)
SimilarPostOption = aliased(PostOption)
post_popularity = db.session.query(func.count(SimilarPost.id)).select_from(
    PostOption).filter(PostOption.post_id == Post.id).correlate(Post
    ).outerjoin(SimilarPostOption, PostOption.val == SimilarPostOption.val
    ).join(SimilarPost, sql.and_(SimilarPost.id == SimilarPostOption.
    post_id, SimilarPost.place_id == Post.place_id)).as_scalar()
How can I query rows with unique values on a joined column?