简体   繁体   中英

SqlAlchemy: How to use the result of a selected subquery inside the where clause

I wish to get a list of articles along with the count of the comments for each article

My query looks like this -

comments_subq = meta.Session.query(func.count(Comment.id)).filter(Comment.article_id==Article.id).as_scalar()

articles = meta.Session.query(Article, comments_subq.label("comment_count"))

articles = articles.filter(column('comment_count') >= 5)

it gives this error

column "comment_count" does not exist LINE 5: WHERE comment_count >= 5

How can I use the count which I selected to filter the result?

Using the Query.subquery() method.

comments_subq = (
    meta.Session.query(
        Comment.article_id,
        func.count(Comment.id).label("comment_count")
    )
    .group_by(Comment.article_id)
    .subquery()
)

articles = (
    meta.Session.query(
        Article, 
        comments_subq.c.comment_count
    )
    .outerjoin(comments_subq, Article.id == comments_subq.c.article_id)
    .filter(comments_subq.c.comment_count >= 5)
)

This works, but is it the most optimal query?

count_subq = meta.Session.query(Comment.article_id, func.count(Comment.article_id) \
    .label("comment_count")) \
    .group_by(Comment.article_id) \
    .subquery()

query = query.add_column(count_subq.c.comment_count.label("comment_count"))

query = query.outerjoin((count_subq, count_subq.c.article_id==Article.id))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM