title: Proper way to prevent SQLAlchemy from re-running queries on expired objects?
body: <p>I'm having trouble wrapping my head around how to deal with expired sqlalchemy objects in a flask request.  Let's say I do something like the following:</p>
  
  <pre><code>from models import Foo, Bar
  
  @app.route("/page")
  def page():
    foos = Foo.query.all()
  
    for foo in foos:
      b = Bar(foo.data)
      db.session.add(b)
  
    db.session.commit()
  
    return render_template('page.html', foos=foos)
  </code></pre>
  
  <p>and then in <code>page.html</code>:</p>
  
  <pre><code>{% for foo in foos %}
    {{ foo. name }}
  {% endfor %}
  </code></pre>
  
  <p>SQLAlchemy will then do a select query for each foo in the template loop, because the <code>session.commit()</code> marked the <code>foos</code> collection as expired.  If I know that there is no way for <code>foos</code> to actually have changed, what is the right way to prevent <code>len(foos)</code> queries from being executed?  Similarly, if <code>foos</code> <em>has</em> changed, what is the right way to refresh the data with a single query rather than many?</p>