Python flask sqlalchemy multi-field query, dynamically change the query statement

suddenly there is an idea that if the field changes are complicated when making a query, you can"t write the query statement, just like
A.query.filter (name=="ds") is written dead. If I need to dynamically switch query fields, especially when there are multiple fields, the idea is to have a function as the query condition, so I can control the output of the function, similar to A.query.filter (fun ()) when fun returns" age==18",
if I need to look up name, or more fields, just change the output of func.

I know that you can"t give a function directly, but usually write a query statement, so that the query is fixed and inflexible.
I wonder if my idea can be implemented (one way is to use eveal () to wrap the entire query, and then modify the filter Filter parameters), is there a better way to implement it?


I am usually encapsulated into a function with multiple parameters. If the parameter is an empty string or-1, it means that there is no such query condition

from sqlalchemy.sql import and_, or_
-sharp 
def get_safety_list(offset, limit, con_date1, con_date2, con_invite, con_name, con_plan, salesman, con_pay):
    try:
        condition = (Safety.id > 0)

        if con_date1 > 0:
            condition = and_(condition, Safety.date >= con_date1)
            condition = and_(condition, Safety.date <= con_date2)

        if con_invite != "":
            condition = and_(condition, Safety.invite.ilike('%' + con_invite + '%'))
        if con_name != "":
            condition = and_(condition,
                             or_(Safety.name.ilike('%' + con_name + '%'), Safety.phone.ilike('%' + con_name + '%')))
        if con_plan != -1:
            condition = and_(condition, Safety.safety_plan == con_plan)

        if len(salesman) > 0:
            condition = and_(condition, Safety.invite.in_(salesman))

        if con_pay != -1:
            condition = and_(condition, Safety.origin == con_pay)

        a = Safety.query.filter(condition)
        count = a.count()
        a = a.order_by(Safety.id.desc()).limit(limit).offset(offset).all()
        return a, count
    except Exception as e:
        logging.error("manager.dbhelper.py get_safety_list exception:" + str(e))
    return (), 0
Menu