cleaning up my SQLAlchemy operations (reducing repetition)

可紊 提交于 2019-12-06 05:24:15

This should help:

from sqlalchemy import inspect
from sqlalchemy.sql.sqltypes import String,Boolean

def filter_model_by_request(qry,model,rv):
    if rv.get('action') == 'filter':
        mapper = inspect(model).attrs # model mapper
        col_names = list(set([c.key for c in mapper]) & set(rv.keys()))
        # col_names is a list generated by intersecting the request values and model column names
        for col_name in col_names:
            col = mapper[col_name].columns[0]
            col_type = type(col.type)
            if col_type == String: # filter for String
                qry = qry.filter(col.ilike('%{0}%'.format(rv.get(col_name))))
            elif col_type == Boolean: # filter for Boolean
                qry = qry.filter(col == '{0}'.format(rv.get(col_name)))
    return qry

Example call (I used it with a @app.before_request and a cURL call to verify):

qry = db.session.query(User)
print filter_model_by_request(qry,User,request.values).count()

The date range filtering is not included in the function, add this feature if you wish, your code is fine for that purpose.

side note: be careful with the bigger/smaller operators for the dates. You're excluding the actual requested dates. Use <= or >= to include dates in filtering action. It's always a pitfall for me..

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!