Dynamic restrictions in SQLAlchemy Core query

后端 未结 1 1782
忘掉有多难
忘掉有多难 2021-01-15 05:31

I want to write a query where I can dynamically pass various restrictions to SQLA Core. For example, I want to be able to specify on a SELECT query WHERE

1条回答
  •  被撕碎了的回忆
    2021-01-15 06:08

    You can build your query dynamically without any problem. For instance, you can do:

    query = select([table])
    for key, value in params.iteritems():
        query = query.where(table.columns[key] == value)
    
    print conn.execute(query).fetchall()
    

    where params is just a dictionary of restrictions such as {'column': 'value'}. This will produce a query in which all the where clauses are chained with AND. Of course, if you need more complex where clauses the construction of the query can be a bit more difficult.

    A working example:

    from sqlalchemy import select
    from sqlalchemy import create_engine
    from sqlalchemy import Column, String, Integer
    from sqlalchemy.schema import MetaData, Table
    
    # create engine and connection
    DB_URI = "mysql+mysqldb://username:password@127.0.0.1:3306/database?charset=utf8mb4"
    engine = create_engine(DB_URI, convert_unicode=True, echo=False)
    conn = engine.connect()
    
    # create table
    metadata = MetaData()
    pieces_table = Table('pieces', metadata,
        Column('id', Integer, primary_key=True),
        Column('size', String(60)),
        Column('color', String(60)),
    )
    metadata.create_all(engine)
    
    # insert data
    conn.execute(pieces_table.insert(), [
        {'size': 'small', 'color': 'blue'},
        {'size': 'large', 'color': 'blue'},
        {'size': 'small', 'color': 'red'},
    ])
    
    # query data
    
    def build_query(table, params):
        query = select([table])
        for key, value in params.iteritems():
            query = query.where(table.columns[key] == value)
        return query
    
    params = {
        'size': 'large',
        'color': 'blue',
    }
    query = build_query(pieces_table, params)
    print conn.execute(query).fetchall()
    

    0 讨论(0)
提交回复
热议问题