0

I have flask app with HTML page and html form for searching students in database with fields like: group_id, first_name, last_name.

In flask app:

if request.method == 'GET':
    args = request.args
    f_name = args.get('first_name')
    l_name = args.get('last_name')
    group_id = args.get('group_id')

stmt = select(Student).where(Student.group_id == group_id,
                             Student.first_name == first_name,
                             Student.l_name = last_name)
    result = db.session.execute(stmt) 

How can I send a query to PostreSQL to search students if not all form fields required to be filled to search by any? This code doesn't work, as some args can be None

Thanks in advance

2
  • First create dictionary of filters and then pass it in where condition . Commented Sep 15, 2022 at 19:47
  • Many thanks! I studied what is dictionary of filters and it worked! Commented Sep 15, 2022 at 20:33

1 Answer 1

1
    filters = {'first_name': args.get('first_name'),
               'last_name': args.get('last_name'),
               'group_id': args.get('group_id')
              }
    for k in list(filters.keys()):
        if filters[k] == '':
            del filters[k]

    query = db.session.query(Student).filter_by(**filters)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.