SQLAlchemy and Alembic 2 · Querying
Group and count
Count rows per group with SQL functions.
from sqlalchemy import func
stmt = select(User.name, func.count(Post.id)).join(Post).group_by(User.name)
rows = session.execute(stmt).all()
Official SQLAlchemy and Alembic 2 documentation