Benjamin
Benjamin

Reputation: 3477

sql alchemy multiple condition in where function

I have a dict like:

{'a': 1, 'b':2, ... }

and an sql alchemy expression like

s = select([some columns]\
.where(put here my dict with a==1 and b==2 and ...)\
.group_by(*[some columns])

but I do not find the correct syntax for the "where" part.

What is the correct way to do this?

Upvotes: 1

Views: 1469

Answers (2)

Dušan Maďar
Dušan Maďar

Reputation: 9879

Convert your conditions dict to an iterable and unpack it in and_ operator.

from sqlalchemy import and_
from sqlalchemy.sql import column

conditions = {'a': 1, 'b':2}
filters = [column(key) == value for key, value in conditions.items()]

s = select([some columns].where(and_(*filters)).group_by(*[some columns])

Upvotes: 4

Ganesan J
Ganesan J

Reputation: 646

In my case data select from table using two where clause

def get_trade_images_by_trade(self,a,b):
    stmt = select([self.table_name]).where(self.table_name.c.column_name.in_([a]))
    stmt = stmt.where(self.table_name.c.column_name.in_([b]))    
    print(stmt)
    result = engine.execute(stmt)
    return result 

Upvotes: 0

Related Questions