I have a problem with a more efficient searching, I have made code in different ways and do not convince me. I'm trying to find an employee with three filters, name, last name and department where he works.
the code in the view is as follows:
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()
As you can see it is a horrible code. if you were to add a filter more would be a combination of 16 statements if, let alone two more.
Any type of response is welcome. Thank you