Conditionally Filtering in SQLAlchemy

后端 未结 1 1153
无人及你
无人及你 2021-01-01 15:49

Is there a way to conditionally add filter arguments to a query in the SQL Alchemy ORM?

For example imagine, I have the following:

q = s         


        
相关标签:
1条回答
  • 2021-01-01 16:37

    Try collecting your queries into a list, and then use the * operator when you call filter:

    queries = [X.y == 'a']
    if b:
        queries.append(X.z == 'b')
    q.filter(*queries)
    

    And BTW I don't understand why you think chaining two filters would change your query, it would correspond to X.y = a AND X.z = b like when you use filter(X.y == 'a', X.z == 'b').

    0 讨论(0)
提交回复
热议问题