20

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

    SELECT "films"."id" AS "megaId", 
           COUNT("filmComments"."id") AS "numOfComments" 
      FROM "films"
INNER JOIN "filmComments" 
        ON ("films"."id" = "filmComments"."filmId") 
  GROUP BY "films"."id";

How can I make the same, using normal SqlAlchemy, without connection.execute(sqlCode)?

P.S. My SqlAlchemy table classes:

from sqlalchemy.ext.declarative import declarative_base
Base = declarative_base()
from sqlalchemy import Column, Integer, String, Date, Float

class Film(Base):
    __tablename__ = "films"
    id = Column(Integer, primary_key = True)
    name = Column(String)
    rating = Column(Float)
    marksCount = Column(Integer)
    commentsCount = Column(Integer, index=True)


class FilmComment(Base):
    __tablename__ = "filmComments"
    id = Column(Integer, primary_key = True)
    filmId = Column(Integer, index=True)
    rating = Column(Integer, index=True)
    text = Column(String)
    votesUp = Column(Integer)
    votesDown = Column(Integer)
    userId = Column(Integer)
    date = Column(Date)
2

1 Answer 1

28

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.

1
  • By the way, I can't test it now, so let me know if there's anything wrong. Commented Nov 9, 2013 at 0:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.