vendredi 30 octobre 2015

SQLAlchemy: Use a function to determine what results a query returns

I want to use a function to determine the which rows are selected in a SQLAlchemy query. Here's the setup...

We have a basic SQLAlchemy mapped object:

class Foo(base):
    foo_id = Column(Integer, primary_key=True)
    foo_data = Column(String(255))

Now if we want to query all the table rows with a specific value for foo_data, we could do something like:

session.query(Foo).filter(Foo.foo_data == 'some data').all()

Now, I want the Foo.foo_data == 'some data' check to take place in a function... so our query looks like:

session.query(Foo).filter(check_foo(Foo.foo_data)).all()

Where check_foo looks like:

def check_foo(foo_data):
    if foo_data == 'foo':
        return True
    else:
        return False

Is this type of thing possible? Obviously for this trivial case, it is really unnecessary, but for a more complex case this would be really useful.

Aucun commentaire:

Enregistrer un commentaire