from sqlalchemy import or_
session.query(
UserModel.id,
UserModel.first_name
).filter(
or_(
UserModel.username == 'john',
UserModel.username == 'michael'
)
).all()
In the code snippet, we are applying OR condition on the username column where it will get the records if its username column has the value 'john' or 'michael'.
We can use the or_ in an SQLAlchemy query where we are joining multiple table models. We can place a filter in the query based on the values of multiple columns that exist inside different tables.
Code Example
session.query(
StudentModel.first_name,
StudentModel.last_name,
ScoreModel.math_score,
ScoreModel.english_score,
).join(
ScoreModel,
StudentModel.id == ScoreModel.student_id,
).filter(
or_(
StudentModel.class_name == "high school",
ScoreModel.section_name == "c"
)
).all()
In the above SQLAlchemy query,
0 Comments