An inner join with SqlAlchemy

前端 未结 1 950
故里飘歌
故里飘歌 2021-01-11 12:48

I have a raw inner join query with counting, written directly on Postgres SQL:

    SELECT \"films\".\"id\" AS \"megaId\", 
           COUNT(\"filmComments\".         


        
相关标签:
1条回答
  • 2021-01-11 13:37

    Mapping that to SQLAlchemy should be quite straightforward. I'm not considering the aliases, for obvious reasons.

    from sqlalchemy import func
    
    megaId, numOfComments = (session.query(Film.id, func.count(FilmComment.id))
                                    .join(FilmComment, Film.id == FilmComment.filmId)
                                    .group_by(Film.id).first())
    

    This should work. The explicit on clause wouldn't be needed if FilmComment.filmId were declared as a foreign key.

    0 讨论(0)
提交回复
热议问题