Skip to content
Advertisement

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?

Advertisement

Answer

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))
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement