SQLALchemy dynamic filter_by

I know that you can create dynamic query filters for SQLAlchemy by supplying **kwargsup filter_by.

for instance

    filters = {'id': '123456', 'amount': '232'}
    db.session.query(Transaction).filter_by(**filters)

Below is my question:

What if I need to request more than or less than? For example (raw SQL):

 select * from transaction t 
 where t.amount > 10 and t.amount < 100;
+4
source share
1 answer

Instead of using it, filter_byI would recommend using it filter, it gives you more options.

For example (from the manual):

db.session.query(MyClass).filter(
    MyClass.name == 'some name',
    MyClass.id > 5,
)

Regarding your case:

filters = (
    Transaction.amount > 10,
    Transaction.amount < 100,
)
db.session.query(Transaction).filter(*filters)
+9
source

Source: https://habr.com/ru/post/1584813/


All Articles