title: Using a function in an SQLAlchemy order_by clause
body: <p>I have an order_by clause in an ORM query:</p>
  <pre><code>def ordering():
      return sqlalchemy.sql.expression.case(
          (User.id == current_user_id(), 1),
          else_=2
      )
  
  ...
  
  query = User.query.order_by(ordering)
  </code></pre>
  <p>But when I try to use this, I get this error:</p>
  <pre><code>sqlalchemy.exc.InvalidRequestError: Can't invoke Python callable current_user_id() inside of lambda expression argument at &lt;code object user_ordering at 0x7fefae4efd40, file &quot;/web/eta/routes/user.py&quot;, line 24&gt;; lambda SQL constructs should not invoke functions from closure variables to produce literal values since the lambda SQL system normally extracts bound values without actually invoking the lambda or any functions within it.  Call the function outside of the lambda and assign to a local variable that is used in the lambda as a closure variable, or set track_bound_values=False if the return value of this function is used in some other way other than a SQL bound value.
  </code></pre>
  <p>I really do want the value to be evaluated every time the query is run.  So I've tried <code>track_bound_values</code>:</p>
  <pre><code>query = User.query.order_by(sqlalchemy.lambda_stmt(ordering, track_bound_values=False))
  </code></pre>
  <p>But this seems to make no difference - I still see the same error.  Is there a way of always using the current value of a function in an ordering expression like this?</p>
  <p>Or, alternatively, is there a better way of making sure a particular value is always returned first?</p>