add_columns()
The add_columns() method helps to add any additional columns or entities to the existing query. As it can be seen in the output the initial query only consisted of the first_name column but later when we used the add_columns() method, we were able to add last_name and course columns as well. Please note that add_column() is deprecated and should be avoided, instead, we can make use of the add_columns() (as shown above) or with_entities() method.
Syntax: sqlalchemy.orm.Query.add_columns(*column)
Where: Add one or more column expressions to the list of result columns to be returned.
Python
from sqlalchemy.orm import sessionmaker import sqlalchemy as db from sqlalchemy.ext.declarative import declarative_base Base = declarative_base() # DEFINE THE ENGINE (CONNECTION OBJECT) engine = db.create_engine( "mysql+pymysql://root:password@localhost/Geeks4Geeks" ) # CREATE THE TABLE MODEL TO USE IT FOR QUERYING class Students(Base): __tablename__ = 'students' first_name = db.Column(db.String( 50 ), primary_key = True ) last_name = db.Column(db.String( 50 ), primary_key = True ) course = db.Column(db.String( 50 ), primary_key = True ) score = db.Column(db. Float ) # CREATE A SESSION OBJECT TO INITIATE QUERY # IN DATABASE Session = sessionmaker(bind = engine) session = Session() # SELECT first_name FROM students result = session.query(Students.first_name) print ( "Query 1:" , result) # SELECT first_name, last_name, course # FROM students result = result.add_columns(Students.last_name, Students.course) print ( "Query 2:" , result) # VIEW THE ENTRIES IN THE RESULT for r in result: print (r.first_name, "|" , r.last_name, "|" , r.course) |
Output:
SQLAlchemy ORM – Query
In this article, we will see how to query using SQLAlchemy ORM in Python.
To follow along with this article, we need to have sqlalchemy and anyone database installed in our system. We have used the MySQL database for this article’s understanding.
Created a Profile table and a Students table:
Here we are going to cover the following methods:
- add_columns()
- add_entity()
- count()
- delete()
- distinct()
- filter()
- get()
- first()
- group_by()
- join()
- one()