sqlalchemy - Programatically generate sql alchemy? -
i have input form 3 input fields. user can choose fill between 1 , 3 of input fields. generating sql alchemy query based on input. if user has not filled out field, should not part of criteria query.
i suppose write code 7 branches -- sql alchemy query each possible query (ex. if user has filled out fields 2 , 3 not 1, query looks this...).
but think there way programmatically generate sql alchemy statement avoid sort of complex branching. there such method?
just chain filters on demand , avoid branching completely:
q = session.query(person) # .join(...).filter(...).order_by(...) # optional filters if form.filter_name: q = q.filter(person.name == form.filter_name) if form.filter_minimum_age: q = q.filter(person.minimum_age >= form.minimum_age) if form.tag_name: q = q.join(tag, person.tags).filter(tag.name.like('%' + form.tag_name + '%')) # iterate on results (only db queried) person in q.all(): # whatever
Comments
Post a Comment