title: SqlAlchemy mapped bulk update - make safer and faster?
body: <p>I'm using Postgres 9.2 and SqlAlchemy. Currently, this is my code to update the rankings of my <code>Thing</code>s in my database:</p>
  
  <pre><code>lock_things = session.query(Thing).\
                  filter(Thing.group_id == 4).\
                  with_for_update().all()
  
  tups = RankThings(lock_things) # return sorted tuple (&lt;numeric&gt;, &lt;primary key Thing id&gt;)
  rank = 1
  for prediction, id in tups:
      thing = session.query(Thing).\
          filter(Thing.group_id == 4).\
          filter(Thing.id == id).one()
      thing.rank = rank
      rank += 1
  
  session.commit()
  </code></pre>
  
  <p>However, this seems slow. It's also something I want to be atomic, which I why I use the <code>with_for_update()</code> syntax.  </p>
  
  <p>I feel like there must be a way to "zip" up the query and so an update in that way. </p>
  
  <p>How can I make this faster and done all in one query?</p>
  
  <hr>
  
  <p><strong>EDIT</strong>: I think I need to create a temp table to join and make a fast update, see:</p>
  
  <p><a href="https://stackoverflow.com/a/20224370/712997">https://stackoverflow.com/a/20224370/712997</a></p>
  
  <p><a href="http://tapoueh.org/blog/2013/03/15-batch-update" rel="nofollow noreferrer">http://tapoueh.org/blog/2013/03/15-batch-update</a></p>
  
  <p>Any ideas how to do this in SqlAlchemy?</p>