简体   繁体   中英

SQLAlchemy (ORM, declarative): How to build query from key/values in a dict?

Using the SQLAlchemy 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. :)

Try the following, references here: Query , filter_by

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

Some example code:

100         COND = and_()
.....
216         if hidxs_sg:$
217             clause = [AM.hidx == hidx for hidx in hidxs_sg]$
218             COND.append(or_(*clause))$
....
300         query = session.query(AM).filter(COND)$

The key is to create an AND condition using and_() and adding the single expressions to the condition....

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