Skip to content

Instantly share code, notes, and snippets.

@maxivak
Created October 20, 2012 21:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save maxivak/3924877 to your computer and use it in GitHub Desktop.
Save maxivak/3924877 to your computer and use it in GitHub Desktop.
Django: raw SQL - SELECT
# file libs/dbutil.py
from itertools import *
from django.db import connection
def query_to_dicts(query_string, *query_args):
cursor = connection.cursor()
cursor.execute(query_string, query_args)
col_names = [desc[0] for desc in cursor.description]
while True:
row = cursor.fetchone()
if row is None:
break
row_dict = dict(izip(col_names, row))
yield row_dict
return
# use in your file
from libs.dbutil import query_to_dicts
results = list(query_to_dicts("SELECT ... FROM yourtable WHERE ... ORDER BY .. "))
for row in results :
# do smth with the row
# access fields by name
name = row['name']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment