Count and Group by in SQLAlchemy ORM Query

tech kamar
Jul 8, 2024

I have 2 Objects

class Post(Base):
__tablename__ = "post"
id = Column(Integer, primary_key=True, autoincrement=True)
user_id = mapped_column(Integer, ForeignKey("user.id"))
content = Column(String(255),nullable=False)
created_date = Column(TIMESTAMP(timezone=False), nullable=False, default=datetime.now())
updated_date = Column(TIMESTAMP(timezone=False), nullable=False, default=datetime.now())

class Like(Base):
__tablename__ = "like"
id = Column(Integer, primary_key=True, autoincrement=True)
user_id = mapped_column(Integer, ForeignKey("user.id"))
post_id = mapped_column(Integer, ForeignKey("post.id"))
created_date = Column(TIMESTAMP(timezone=False), nullable=False, default=datetime.now())
updated_date = Column(TIMESTAMP(timezone=False), nullable=False, default=datetime.now())

Now my aim is to find the number of likes for each post.

Here is how to do it.

from sqlalchemy import func
result = db_session.query(Post.id,Post.content,Post.created_date,func.count(Like.id)).join(Like,isouter=True).group_by(Post.id).all()

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

No responses yet

Write a response