absent1706/sqlalchemy-mixins

Contributing code - extending filter logic

Opened this issue · 2 comments

Hi,

I've been using sqlalchemy-mixins in a project recently and found it really useful. One thing I wanted to be able to do was to have more complex logic when filtering objects. To lift your example from the docs - show all posts that are either public or have no user.

I had a bit of a hack around and extended smart_query to take dictionaries of the form:

from sqlalchemy import or_
Comment.smart_query(filters={ or_: {
    'post___public': True, 
    'user__isnull': False
}})

This seems to work well, though it's a bit ugly to use functions as dictionary keys and it only works with smart_query, not where if the function is at the top level (function kwargs need to be strings)

Comment.where(**{or_: {...}})
TypeError...

I've got tests, docs etc. in my branch here: fredludlow/sqlalchemy-mixins@master...filter-operators
If you like it then I can make a PR. If you don't like it in its current state but can think of another good way to do this I'm all ears!

Update: I have a nagging thought that this is all a bit too much, but anyway, I pushed an update that allows nesting lists as well as dictionaries, which means you can now express things like (X OR Y) AND (W OR Z).

Comment.smart_query(filters=[{or_: {'x': 5, 'y': 6}}, {or_: {'z': 1, 'w': 2 }} ])
# where (x=5 or y=6) and (z=1 or w=2)

See updated example for more details

(If this is all possible already and I'm missing something fundamental please let me know : ))