【问题标题】:Python, SqlAlchemy. How to make a more efficient search?Python,SqlAlchemy。如何进行更高效的搜索?
【发布时间】:2015-12-07 07:01:57
【问题描述】:

我对更有效的搜索有疑问,我以不同的方式编写代码并且无法说服我。我正在尝试查找具有三个筛选条件的员工,即姓名、姓氏和他工作的部门。

视图中的代码如下:

if form.nombre.data == u'' and form.apellido.data == u'' and form.departamento.data != u'':
    empleados = db.session.query(Empleado).filter_by(departamento_id=form.departamento.data).all()

elif form.nombre.data == u'' and form.apellido.data != u'' and form.departamento.data == u'':
    empleados = db.session.query(Empleado).filter_by(apellido=form.apellido.data.lower()).all()

elif form.nombre.data == u'' and form.apellido.data != u'' and form.departamento.data != u'':
    empleados = db.session.query(Empleado).filter_by(apellido=form.apellido.data.lower(),
                                                         departamento_id=form.departamento.data).all()

elif form.nombre.data != u'' and form.apellido.data == u'' and form.departamento.data == u'':
    empleados = db.session.query(Empleado).filter_by(nombre=form.nombre.data.lower()).all()

elif form.nombre.data != u'' and form.apellido.data == u'' and form.departamento.data != u'':
    empleados = db.session.query(Empleado).filter_by(nombre=form.nombre.data.lower(),
                                                         departamento_id=form.departamento.data).all()

elif form.nombre.data != u'' and form.apellido.data != u'' and form.departamento.data == u'':
    empleados = db.session.query(Empleado).filter_by(nombre=form.nombre.data.lower(), apellido=form.apellido.data.lower()).all()

elif form.nombre.data != u'' and form.apellido.data != u'' and form.departamento.data != u'':
    empleados = db.session.query(Empleado).filter_by(nombre= form.nombre.data.lower(), apellido=form.apellido.data.lower(), departamento_id=form.departamento.data).all()

else:
    empleados = db.session.query(Empleado).all()

如您所见,这是一个可怕的代码。如果您要添加一个过滤器,更多将是 16 个语句的组合 if,更不用说另外两个了。

欢迎任何类型的回复。谢谢

【问题讨论】:

    标签: python sql sqlalchemy flask-sqlalchemy


    【解决方案1】:

    只需构建查询,例如:

    query = db.session.query(Empleado)
    
    if form.nombre.data != '':
        query = query.filter_by(nombre=form.nombre.data.lower())
    if form.apellido.data != '':
        query = query.filter_by(apellido=form.apellido.data.lower())
    if form.departamento.data != '':
        query = query.filter_by(departamento_id=form.departamento.data)
    
    print query.all()
    

    【讨论】:

    • 感谢您的帮助。 :D
    【解决方案2】:

    您可能想要使用 or_ 或 and_ 过滤器。喜欢:

    from sqlalchemy import or_
    filter(or_(User.name == 'ed', User.name == 'wendy'))
    

    另请参阅tutorial 和此post

    【讨论】:

      猜你喜欢
      • 2016-01-19
      • 2016-04-19
      • 1970-01-01
      • 1970-01-01
      • 2016-08-15
      • 2015-10-31
      • 2018-01-29
      • 1970-01-01
      • 2015-12-07
      相关资源
      最近更新 更多