Iterating over a database column in Django

Posted by curious on Stack Overflow See other posts from Stack Overflow or by curious
Published on 2010-04-07T19:30:17Z Indexed on 2010/04/07 19:33 UTC
Read the original article Hit count: 170

Filed under:
|
|
|

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:

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()

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.

© Stack Overflow or respective owner

Related posts about django

Related posts about mysql