sqlalchemy-mixins icon indicating copy to clipboard operation
sqlalchemy-mixins copied to clipboard

Contributing code - extending filter logic

Open fredludlow opened this issue 5 years ago • 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: https://github.com/fredludlow/sqlalchemy-mixins/compare/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!

fredludlow avatar Oct 15 '20 21:10 fredludlow

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 : ))

fredludlow avatar Oct 20 '20 10:10 fredludlow

Hi Fred! Thank you for your contribution to the code! Would you mind creating a PR to the original repo?

On Tue, Oct 20, 2020 at 1:25 PM Fred Ludlow [email protected] wrote:

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 https://github.com/fredludlow/sqlalchemy-mixins/blob/57a7a8f763ead72308c03b037385ba4bdff9b879/examples/smartquery.py#L418 for more details

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

— You are receiving this because you are subscribed to this thread. Reply to this email directly, view it on GitHub https://github.com/absent1706/sqlalchemy-mixins/issues/47#issuecomment-712753160, or unsubscribe https://github.com/notifications/unsubscribe-auth/AAMJAIYAMEKPJN7ENVCOEFLSLVQSZANCNFSM4SSRLOSA .

absent1706 avatar Oct 20 '20 11:10 absent1706