Chrome Extension

Apply condition based multiple filters in SQLAlchemy query

To apply multiple filters in SQLAlchemy queries which are condition-based you can use ** before queries object and pass it to the filter method.
all_filters = [UserModal.role == 'admin']

if user.last_name:
    all_filters.append(UserModal.last_name == 'Deo')

db.session.query(
    UserModal.username
).filter(
    **all_filters
).all()
Best JSON Validator, JSON Tree Viewer, JSON Beautifier at same place. Check how cool is the tool

In the code snippet, we are applying two filters on UserModel. First filter [UserModal.role == 'admin'] will be applied every time. But the second filter 'UserModal.last_name == 'Deo' will be applied if it will satisfy the condition user.last_name.

Was this helpful?
0 Comments