count()
The count() method is a synonym to the COUNT we use in the SQL queries. It returns the number of records present in the table. In our case, the students table consists of 12 records, the same can be verified from the students table screenshot shown at the beginning.
Syntax: sqlalchemy.orm.Query.count()
Return a count of rows this the SQL formed by this Query would return.
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 * FROM PROFILE result = session.query(Students).count() # VIEW THE RESULT print ( "Count:" , result) |
Output:
Count: 12
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()
Contact Us