python

Column name as alias name SQLAlchemy

We can show column names of a table with its alias name using the .label() method in SQLAlchemy.

employees = self.session.query(
                EmployeeModel.id,
                EmployeeModel.name.label("emp_name") #we are using emp_name alias for column name
            ).filter(
                EmployeeModel.department == 'finance'
            ).all()

We can select a column with its alias name using the .label() method in SQLAlchemy. Sometimes we got the requirements to show a function result or column name with a different name, you can use the .label() method there.

Below is an example of getting the sum of column values named score and we are showing it with its alias name total_score.

+----+----------+--------+
| Id | name     | score  |
+----+----------+--------+
| 1  | Math     | 10     |
| 2  | Physics  | 30     |
| 3  | Math     | 20     |
| 4  | Math     | 50     |
+----+----------+--------+

The SQLAlchemy query will be as below

result = db.session.query(
            SubjectModel.name,
            func.sum(SubjectModel.score).label("total_score")
        ).filter(
            SubjectModel.name== 'Math'
        ).group_by(
            SubjectModel.name
        ).all()
Was this helpful?