Home > Blockchain >  Exact match with filter() Flask
Exact match with filter() Flask

Time:07-18

I'am new to python and iam coding a small webapp to search in a database. Its fonctionnal but doesnt function well.

Example : If i search for a 'lieu', a 'Annee' and a 'Signataire' it doesnt give me the exact matches, instead it gives me every 'Signataire' even if its not the 'Annee' or the 'lieu' that i was looking for.

Here is the code :

'''

def search_results(search):

    results = []
    lieu = search.data['Lieu']
    annee = search.data['Annee']
    signataire = search.data['Signataire']
    cote = search.data['Cote']


    if search.data['Lieu'] or search.data['Annee'] or 
    search.data['Cote']:
        qry = db_session.query(Cote).filter(and_(Cote.lieu.contains(lieu),Cote.annee.contains(annee),Cote.cote.contains(cote))
    )
        



    results = qry.all()

    if search.data['Signataire']:
        qry = db_session.query(Cote).filter(or_(Cote.signataire_nom.contains(signataire),Cote.signataire_titre.contains(signataire)))
   
        results = qry.all()

    if not results:
        flash('No results !')
        return redirect('/')

    else:
        table = Results(results)
        table.border = True
        return render_template('results.html', table=table)

'''

CodePudding user response:

This is because you are using "if" the second time and not "elif". So if there exists the Signataire, then your results are always all the signataire. To resolve this you should use something like this:

def search_results(search):

results = []
lieu = search.data['Lieu']
annee = search.data['Annee']
signataire = search.data['Signataire']
cote = search.data['Cote']


if search.data['Lieu'] or search.data['Annee'] or search.data['Cote']:
    qry = db_session.query(Cote).filter(and_(
        Cote.lieu.contains(lieu),Cote.annee.contains(annee),Cote.cote.contains(cote))
    )

    results = qry.all()

elif search.data['Signataire']:
    qry = db_session.query(Cote).filter(or_(
        Cote.signataire_nom.contains(signataire),Cote.signataire_titre.contains(signataire)))

    results = qry.all()

if not results:
    flash('No results !')
    return redirect('/')

else:
    table = Results(results)
    table.border = True
    return render_template('results.html', table=table)

Please add the indent to all the other lines except the define function line**

  • Related