MVr
MVr

Reputation: 128

Sqlalchemy filter on object

I have a script that will test some conditions of objects in a SQLAlachemy ORM driven database. This will all be dynamic and that's given me some problems.

I want to query the minimum amount of objects for all tests, therefor all tests have a default filtering. If I were to test 2 tests, both filters will be applied to the query so I get the minimal amount of objects.

class Employee(Base):
    name = Column(String ...)
    account = Column(Account ...)
    coworkers = relationship(Employee_coworker, use_list=True ...)
    ...

So when I get all objects, I want to use my 2 filters

filter_1 = Employee.account != None
filter_2 = Employee.coworkers.any()
for e in session.query(Employee).filter(or_(filter_1, filter_2)).all():
    # IF e is here because of filter_1: 
    # Do something
    # IF e is here because of filter_2:
    # Do this thing
...

Is it possible to test an object by the same way a query gets filtered?

Upvotes: 3

Views: 4448

Answers (1)

univerio
univerio

Reputation: 20548

You can explicitly ask the database to tell you what matched:

filter1 = ...
filter2 = ...
filters = [filter1, filter2, ...]
query = session.query(Employee, *filters).filter(or_(*filters))
for employee, filter1_applied, filter2_applied, ... in query:
    ...

Upvotes: 4

Related Questions