title: Iterating over a database column in Django
body: <p>I would like to iterate a calculation over a column of values in a MySQL database. I wondered if Django had any built-in functionality for doing this. Previously, I have just used the following to store each column as a list of tuples with the name table_column:</p>
  
  <pre><code>import MySQLdb
  import sys
  
  try:
      conn = MySQLdb.connect (host = "localhost",
                              user = "user",
                              passwd="passwd",
                              db="db")
  except MySQLdb.Error, e:
      print "Error %d: %s" % (e.args[0], e.args[1])
      sys.exit (1)
  
  cursor = conn.cursor()
  
  for table in ['foo', 'bar']:
      for column in ['foobar1', 'foobar2']:
          cursor.execute('select %s from %s' % (column, table))
          exec "%s_%s = cursor.fetchall()" % (table, column)
  
  cursor.close()
  
  conn.commit()
  conn.close()
  </code></pre>
  
  <p>Is there any functionality built into Django to more conveniently iterate through the values of a column in a database table? I'm dealing with millions of rows so speed of execution is important.</p>
  
  <p><b>[SOLVED]</b> Thanks everyone. I used the built-in iterator, combined with the values_list() call for performance optimization. Note that calling values() will return dicts, which are slow to iterate over, whereas values_list() returns much faster tuples. So, for example, if I want to iterate over every row of the column 'foobar1', in the table 'foo', I can obtain an iterator in the following way:</p>
  
  <pre><code>foobar1_iterator = foo.objects.values_list('foobar1').iterator()
  </code></pre>
  
  <p>Suppose I want to iterate over i to produce a list of all row values of 'foobar1'. Then simply do this:</p>
  
  <pre><code>foobar1_list = [i for i in foobar1_iterator]
  </code></pre>