Answer the question
In order to leave comments, you need to log in
How to build a SQLAlchemy query so that when the filter is set to None, all table rows are returned?
There are several variables.
a = 23
b = 45
c = 67
query_result = User.query.filter(User.id == a, User.group == b, User.key == c).all()
query_result = User.query.filter(User.group == b, User.key == c).all()
Answer the question
In order to leave comments, you need to log in
from sqlalchemy import or_
query_result = User.query.filter(or_(a == None, User.id == a),
or_(b == None, User.group == b),
or_(c == None, User.key == c))
Made so:
1. Created object of request.
2. Using the if construct, I add filters and redefine the query to apply a chain of filters.
if a not None:
query_result = query_result.filter(User.id == a)
if b not None:
query_result = query_result.filter(User.group == b)
if c not None:
query_result = query_result.filter(User.key == c)
If this is a function code, then add the parameter a=None. Something like
def func(a=None):
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question