Skip to content Skip to sidebar Skip to footer

Sqlalchemy: Avoid Query Filter If Searched Value Is None

Is there a one-liner to handle the following scenario: def queryByAttr(attr1,attr2=None): if attr2 is None: session.query(Foo).filter(Foo.attr1==attr1) else: session.qu

Solution 1:

There is a more readable multi-liner using chaining:

defqueryByAttr(attr1, attr2=None):
    q = session.query(Foo).filter(Foo.attr1==attr1)
    ifnot(attr2 isNone):
        q = q.filter(Foo.attr2==attr2)
    return q

and you can make it a (rather long) one-liner as well:

defqueryByAttr(attr1, attr2=None):
    return (session.query(Foo).filter(Foo.attr1==attr1)) if (attr2 isNone) else (session.query(Foo).filter(Foo.attr1==attr1).filter(Foo.attr2==attr2))

All this assuming you never need a query to return those Foos which have attr2 value NULL.

Solution 2:

Can also use.

defqueryByAttr(attr1, attr2=None):
    return (session.query(Foo).filter((*[Foo.attr1==attr1, Foo.attr2==attr2] if attr2 else *[Foo.attr1==attr1])))

Post a Comment for "Sqlalchemy: Avoid Query Filter If Searched Value Is None"