SQLAlchemy (ORM, declarative): How to build query from key/values in a dict?
Question: Using the [SQLAlchemy](http://www.sqlalchemy.org/) ORM (declarative form), how
do you programatically create a query from a set of conditions in a
dictionary?

I wish to search for those records in a users table that match some criteria
previously collected in a dict. I can not know in advance which fields will be
used, and must be able to handle that some fields are Integers, some are
Strings, that there can be a lot of different fields, etc.

Example:

    
    
    from sqlalchemy import Column, Integer, String
    from sqlalchemy.ext.declarative import declarative_base
    
    Base = declarative_base()
    class User(Base):
        __tablename__ = 'users'
    
        id = Column(Integer, primary_key=True)
        name = Column(String)
        email = Column(String)
    

Two queries has been requested, resulting in the following dicts:

    
    
    q1_dict = {'id' : 177}
    
    q2_dict = {'name' : 'Johnny', 'email' : 'johnny@somewhere.com'}
    

Are there any simple/generic way I can create my queries from those two dicts,
simply relying on the fact that the keys match the attributes of the User
class, while handling types correctly, autoescaping unsafe values, etc?

I've spent several hours googling this, and browsing the SQLAlchemy
documentation, but can't seem to find any good answers/examples.

**Solution:**

So, after the help from you guys, the solution seems to be as simple as:

    
    
    User.query.filter_by(**q1_dict)
    
    User.query.filter_by(**q2_dict)
    

...to get to the two queries needed in the example.

I had already looked at the links you provided, dagoof, but I guess my
"python" just wasn't strong enough to get to the solution on my own. :)


Answer: Try the following, references here:
[Query](http://www.sqlalchemy.org/docs/orm/query.html#sqlalchemy.orm.query.Query),
[filter_by](http://www.sqlalchemy.org/docs/orm/query.html#sqlalchemy.orm.query.Query.filter_by)

    
    
    session.query(User).filter_by(**q1_dict)
    

