Search code snippets, questions, articles... Chrome Extension

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(
      "emp_name") #we are using emp_name alias for column name
                EmployeeModel.department == 'finance'
Best JSON Validator, JSON Tree Viewer, JSON Beautifier at same place. Check how cool is the tool

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(
Was this helpful?
Join Devsheet Ask a Question