Created
August 6, 2012 14:57
-
-
Save Apkawa/3275040 to your computer and use it in GitHub Desktop.
wrap raw_sql for make dict result with fields names
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
from django.db import connection | |
class DictQuery(object): | |
def __init__(self, query, params=()): | |
self.query = query | |
self.params = params | |
self._cursor = None | |
self._iterator = None | |
def __iter__(self): | |
return self | |
@property | |
def fields(self): | |
self._execute() | |
return [f[0] for f in self._cursor.description] | |
@property | |
def rowcount(self): | |
self._execute() | |
return self._cursor.rowcount | |
def _execute(self): | |
if self._cursor is None: | |
self._cursor = connection.cursor() | |
self._cursor.execute(self.query, self.params) | |
def _get_iterator(self): | |
self._execute() | |
fields = self.fields | |
for row in self._cursor.fetchall(): | |
yield dict(zip(fields, row)) | |
def next(self): | |
if self._iterator is None: | |
self._iterator = self._get_iterator() | |
return self._iterator.next() | |
def fetchall(self): | |
return list(self) | |
def fetchone(self): | |
return self.next() | |
def dict_execute(query, params=()): | |
return DictQuery(query, params) |
Хотя почитал код и не нашел аналогии, для чего он? Приведи примеры, плизз
Ну, в питоновской реализации курсора http://www.python.org/dev/peps/pep-0249/ нет этого.
Написал ленивую обертку, вот.
Словарь еще можно на namedtuples заменить
В общем, да, костыли, но иногда хочется по нормальному делать raw запросы без лишних полей (например, сразу в csv/xls и еще куда то)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Это аналог MySQLdb.cursors.DictCursor?
In [9]: c.fetchallDict()
Out[9]:
({'app_name': 'subhub',
'applied': datetime.datetime(2012, 7, 31, 11, 10, 25),
'id': 1L,
'migration': '0001_initial'},
{'app_name': 'scipio',
'applied': datetime.datetime(2012, 7, 31, 11, 11, 59),
'id': 2L,
'migration': '0001_initial'})