Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 280
NoPyGod Avatar asked May 17 '13 04:05

NoPyGod


2 Answers

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)
)
like image 52
jackotonye Avatar answered Nov 06 '22 09:11

jackotonye


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))
like image 36
NoPyGod Avatar answered Nov 06 '22 07:11

NoPyGod