Expression of common filter conditions in SQLAlchemy ORM query

When using SQLAlchemy ORM to query data, if the required records are filtered according to the selected conditions, you can refer to the relevant methods described in this article. There's no skill, just familiarity. Use the data source I often use Sample Data . It is recommended to use jupyter notebook for interactive testing.

Using SQLAlchemy ORM involves engine, session and other objects. Before querying, prepare the following codes:

from sqlalchemy import create_engine
from sqlalchemy import Column, String, Integer, and_, or_
from sqlalchemy.orm import sessionmaker
from sqlalchemy.ext.declarative import declarative_base

engine = create_engine('mysql+pymysql://root:pwd@localhost:3306/stonetestdb?charset=utf8')

Base = declarative_base(engine)

Session = sessionmaker(engine)
session = Session()

class EmpMaster(Base):
    __tablename__ = 'emp_master'

    EMP_ID = Column(Integer, primary_key=True)
    GENDER = Column(String(10))
    AGE = Column(Integer)
    EMAIL = Column(String(50))
    PHONE_NR = Column(String(20))
    EDUCATION = Column(String(20))
    MARITAL_STAT = Column(String(20))
    NR_OF_CHILDREN = Column(Integer)
    def __str__(self):
        return '<Employee({}, {}, {}, {}, {}, {}, {}, {}, {})>'.format(
def print_emps(emps):
    for emp in emps:

In the EmpMaster class, the function of defining the str method is to facilitate calling the output display of the code. The print_emps() method reduces the amount of code when printing multiple empmasters.

Filter by primary key

The first method uses the get() method of the Query object.

# filter by primary key
emp = session.query(EmpMaster).get(1001)

The session.query() method returns the sqlalchemy.orm.query.Query object instance. Call the get() method of the query object and press the primary key to get the record.

The second method uses the filter_by() method of the Query object. The parameter of the filter_by() method is a keyword, which is relatively simple to use, but not powerful enough.

# fiter by primary key method 2
emp = session.query(EmpMaster).filter_by(EMP_ID = 1001).first()

Method 3, use the fitter() method of the Query object. The parameter of this method is SQL Expression of sqlalchemy ORM, which is relatively complex, but very powerful. Why it is powerful? I will explain it with examples later. For example, just now, filter by primary key. The filter by () method is as follows:

emp = session.query(EmpMaster).filter(
    EmpMaster.EMP_ID == 1001

The parameter of the filter() method is sql expression. For example, in this example, EmpMaster.EMP_ID is a Column. By looking at the source code of the Column, we can see that the Column object has like, in_, contains and other methods, so it can express complex filter conditions.

Equal and not equal

Later, we use the filter() method to learn how to express the filter conditions. Just now we have demonstrated equal (= =), if you want to express not equal, use the! = operator:

emps = session.query(EmpMaster).filter(
    EmpMaster.EMP_ID != 1001


AND condition

If there are multiple filter conditions, and the relationship between these conditions is and, there are two expression methods. One is that the conditions are separated by commas. The default relationship is and. The second method is to use and

emps = session.query(EmpMaster).filter(
    EmpMaster.EMP_ID <= 1009, EmpMaster.GENDER == 'Female'



emps = session.query(EmpMaster).filter(
    and_(EmpMaster.EMP_ID <= 1009, EmpMaster.GENDER == 'Female')

Note that and? Needs to be imported.

OR condition

Or the condition needs to use or and needs to be imported.

emps = session.query(EmpMaster).filter(
    or_(EmpMaster.GENDER == 'Female', EmpMaster.NR_OF_CHILDREN == 0)

fuzzy search

There are two methods of fuzzy search: contains or like. For example, we want to query the people with west string in EMAIL:

emps = session.query(EmpMaster).filter(


emps = session.query(EmpMaster).filter('%west%')


If you want to select from several strings, use the in U keyword as the query criteria, and the parameter is a list. For example, the following query means to find employees with master's degree or doctor's degree:

emps = session.query(EmpMaster).filter(
    EmpMaster.EDUCATION.in_(['Doctorial', 'Master'])
192 original articles published, 150 praised, 470000 visitors+
His message board follow

Tags: Session SQL jupyter MySQL

Posted on Sat, 07 Mar 2020 08:28:57 -0500 by ams007