SQLAlchemy query to PostgreSQL with arbitrary filled form's fields

Viewed 18

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

1 Answers
    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)
Related