filter()
The filter() method works like the WHERE clause in SQL. It takes in an expression and returns only those records which satisfy the provided expression. There can be one or more expressions separated by ‘&‘. In the example, we have provided the LIKE condition for the name column in the profile table.
Syntax: sqlalchemy.orm.Query.filter(*criterion)
Apply the given filtering criterion to a copy of this Query, using SQL expressions.
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 Profile(Base): __tablename__ = 'profile' email = db.Column(db.String( 50 ), primary_key = True ) name = db.Column(db.String( 100 )) contact = db.Column(db.Integer) # CREATE A SESSION OBJECT TO INITIATE QUERY IN DATABASE Session = sessionmaker(bind = engine) session = Session() # SELECT email FROM student WHERE name LIKE 'Amit%'; result = session.query(Profile) \ .with_entities(Profile.email) \ . filter (Profile.name.like( 'Amit%' )). all () # VIEW THE ENTRIES IN THE RESULT for r in result: print ( "\n" , r.email) |
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()
Contact Us