4

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?

1 Answer 1

5

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.