Created
October 20, 2012 21:29
-
-
Save maxivak/3924877 to your computer and use it in GitHub Desktop.
Django: raw SQL - SELECT
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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