tsudot
tsudot

Reputation: 543

How to create custom filter_by in SQLAlchemy

I want to create a slightly more complex filter_by - such that if I pass some kwargs and values, and some are None, then those aren't included in the filter. I'm not sure how to override filter_by globally.

Effectively what I'm looking for is:

data = {'is_enabled': True, 'city': 'SF', 'address': None}
query.smart_filter(data)

and smart_filter excludes the 'address' field and calls filter_by with 'is_enabled' and 'city' values.

Is there any way I could build something like this?

Upvotes: 4

Views: 1059

Answers (1)

benselme
benselme

Reputation: 3197

Subclass sqlalchemy.orm.Query, add your smart_filter method, and then pass the new class to your sessionmaker. Something along those lines:

class MyQuery(Query):
    def smart_filter(self, **kwargs):
        kwargs = {key: value for key, value in kwargs.items() 
                  if value is not None}
        return self.filter_by(**kwargs)

Session = sessionmaker(query_cls=MyQuery)

Upvotes: 5

Related Questions