python

Count Rows group by column name SqlAlchemy

Group by in SQLAlchemy can be applied using the group_by() method. In the code example we are trying to get the counts of users according top their roles.

user_counts = session.query(
                UserModel.role, 
                func.count(UserModel.role).label("total_counts")
            ).group_by(
                UserModel.role
            ).all()

#THE ABOVE QUERY CAN OUTPUT DATA:
#  +-------------+----------------+
#  | role        | total_counts   |
#  +-------------+----------------+
#  | Admin       | 100            |
#  | Super Admin | 50             |
#  | user        | 1700           |
#  +-------------+----------------+
Was this helpful?