简体   繁体   中英

SQLAlchemy filter by dict of lists

Trying to make a query in flask_sqlalchemy. I want to filter using a dict of lists and using ORM not a query string. Still new to SQLAlchemy so any help would be appreciated.

I know I can do:

filter = {
'name': 'apple'
, 'age': 14
}

Items.query.filter(**filter).all()

Which translates to:

SELECT * FROM items WHERE name = 'apple' AND age = 14;

But I want:

filter = {
'name': ['apple', 'pear']
, 'age': [14, 15, 21]
}

To be:

SELECT * FROM items WHERE name IN ('apple', 'pear') AND age IN (14, 15, 21);

This seems to do the trick:

filter = {
    'name': ['apple', 'pear']
    , 'age': [14, 15, 21]
}    

items = Item.query

for field in query:
    items = items.filter(getattr(Item, field).in_(query[field]))

items = items.all()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM