R
R
REDkiy2016-05-31 11:21:23
Python
REDkiy, 2016-05-31 11:21:23

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

I am making this request:
query_result = User.query.filter(User.id == a, User.group == b, User.key == c).all()

Question: It is necessary that if there is no variable a or if a = None , a query like this is executed:
query_result = User.query.filter(User.group == b, User.key == c).all()

That is, lines with all possible User.id were issued .
Is it possible to do without the if ... elif ... else construct and several different queries?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
DDDsa, 2016-05-31
@REDkiy

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))

R
REDkiy, 2016-06-03
@REDkiy

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)

3. I receive the data from the database.
We need constructive criticism of this approach.

V
Vyacheslav, 2016-05-31
@Firik67

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 question

Ask a Question

731 491 924 answers to any question