12
votes

I have just started using SQLAlchemy. I decided to use it because I was using a lot of string expression in the middle of my sqlite queries.

So, that is my problem. I have a table with many equipment and each of them has dates for level of maintanance. The point is that the user can select the maintance level he wants to see on the screen. So, I should "adjust" my SQLAlchemmy for each combination of maintanance level he's chosen.

For exemple, in the raw SQLite.

SELECT * WHERE (equipment IN []) AND m_level1 = DATE AND m_level2 = DATE ....)

So, it is possible to have many combination for each if condition, it depends which checkboxes are checked. As I mentioned, in the raw SQL I used a lot of string to reach my goal. But I want to improve the code using SQLAlchemy.

Sorry I do not have the code now ! Thank you all !

3
Welcome to Stack Overflow! Would you be able to post enough code to help us understand what you've tried, so we can work with something close to a Minimal, Complete, and Verifiable Example (MCVE)? - Isiah Meadows
Sure. Please take a look at my next answer. It is pretty working, but I am not sure if it is the right think to do. The point is that I wanted the conditions to be dynamic and with that code I got it. - Lorenzo Simonassi

3 Answers

26
votes

I assume you are using the ORM.

in that case, the filter function returns a query object. You can conditionaly build the query by doing something like

query = Session.query(schema.Object).filter_by(attribute=value)
if condition:
    query = query.filter_by(condition_attr=condition_val)
if another_condition:
    query = query.filter_by(another=another_val)

#then finally execute it

results = query.all()
14
votes

The function filter(*criterion) means you can use tuple as it's argument, @Wolph has detail here: SQLALchemy dynamic filter_by for detail

3
votes

if we speak of SQLAlchemy core, there is another way:

from sqlalchemy import and_


filters = [table.c.col1 == filter1, table.c.col2 > filter2]
query = table.select().where(and_(*filters))

If you're trying to filter based on incoming form criteria:

form = request.form.to_dict()
filters = []
for col in form:
    sqlalchemybinaryexpression = (getattr(MODEL, col) == form[col])
    filters.append(sqlalchemybinaryexpression)
query = table.select().where(and_(*filters))

Where MODEL is your SQLAlchemy Model