简化动态sqlalchemy迭代request.args

时间:2018-04-17 21:06:10

标签: python flask flask-sqlalchemy

我无法将所有这些碎片放在一起。我从表单POST获取值表单中的名称/ id是我的数据库表中的实际列名。

这里的想法是过滤级联select2输入以创建动态过滤器。例如,我当前的3个选择名称是字段,名称。如果我选择I字段,我只想提供该字段中的名称。如果没有选择字段,我提供所有名称(等等)。显然,生产模型将超过2个。

我正在尝试迭代request.args以获取名称和值,然后添加到过滤器。下面是我的代码。

@bp.route('/wells/name')
def wells_name():
    if request.args:
        qry = Wells.query
        for var in request.args:
            qry = qry.filter(getattr(Wells, var) == request.args['{}'.format(var)])
        query = qry.with_entities(Wells.name).group_by(Wells.name).order_by(Wells.name)
    else:
        query = Wells.query.with_entities(Wells.name).group_by(Wells.name) \
            .order_by(Wells.name)

我使用以下代码来获取变量的值;

request.args['{}'.format(var)]

以下代码表示Wells.variablename(此场景中的Wells.field或Wells.name)

getattr(Wells, var)

以及以下示例尝试“将它们放在一起”https://stackoverflow.com/questions/39137911/build-dynamic-filters-in-sqlalchemy-python

1 个答案:

答案 0 :(得分:0)

好的,这个问题绝对不是我所预料的。我在迭代迭代之前移动了with_entities,它解决了问题。我确信仍有改进的余地,但它比我所拥有的大大改善。这是新代码。

@bp.route('/wells/name')
def wells_name():
    if request.args:
        query = Wells.query.with_entities(Wells.field, Wells.name) \
            .group_by(Wells.field, Wells.name).order_by(Wells.name)
        for var in request.args:
            query = query.filter(getattr(Wells, var) \
                .ilike('%{}%'.format(request.args['{}'.format(var)])))
    else:
        query = Wells.query.with_entities(Wells.name).group_by(Wells.name) \
            .order_by(Wells.name)

旧代码

@bp.route('/wells/name')
def wells_name():
    if 'field' in request.args and 'name' not in request.args:
        field = request.args['field']
        query = Wells.query.filter(Wells.field.ilike('%{}%'.format(field))) \
            .with_entities(Wells.name).group_by(Wells.name).order_by(Wells.name)
    elif 'field' not in request.args and 'name' in request.args:
        name = request.args['name']
        query = Wells.query.filter(Wells.name.ilike('%{}%'.format(name))) \
            .with_entities(Wells.name).group_by(Wells.name).order_by(Wells.name)
    elif 'field' in request.args and 'name' in request.args:
        field = request.args['field']
        name = request.args['name']
        query = Wells.query.filter(Wells.field.ilike('%{}%'.format(field)), \
            Wells.name.ilike('%{}%'.format(name))) \
            .with_entities(Wells.name).group_by(Wells.name).order_by(Wells.name)
    else:
        query = Wells.query.with_entities(Wells.name).group_by(Wells.name) \
            .order_by(Wells.name)

显然有更多变量的旧代码'即使只增加了第三名,也会显着增长。