samedi 14 décembre 2019

SQLAlchemy ORM / Python: one-liner to include query filter only if searched value is not None (inline 'if')

Can I implement in Python an inline if at the method level?

Let's take this (simplified) situation:

# DB-level 'or'
db.session.query(TableClass).filter(or_(TableClass.column_1 == value_1,
                                        TableClass.column_2 == value_2)).first()

# basic Python-level 'if'
if value_1:
    db.session.query...value_1
if value_2:
    db.session.query...value_2

Instead of querying DB or adding additional if statements as per above, is it possible to achieve the same inline with something like:

# desired inline Python 'if' at method level
db.session.query(TableClass).filter({
           if value_1 TableClass.column_1 == value_1 \
           else if value_2 TableClass.column_2 == value_2 else None
    }).first()

# ^-- or something similar at method level

Alternatively, have a part of the SQLAlchemy filter be active only when the underlying value exists.

The main motivation here is DRY and avoiding DB search of None values.

Tried inline combination of starred expression and if statement as suggested:

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

but I get SyntaxError: invalid syntax at if.

Aucun commentaire:

Enregistrer un commentaire