Skip to content

Instantly share code, notes, and snippets.

@Gera3dartist
Forked from Suor/gist:876324
Last active September 7, 2015 21:41
Show Gist options
  • Save Gera3dartist/e0e0bef739fc0bc95a2d to your computer and use it in GitHub Desktop.
Save Gera3dartist/e0e0bef739fc0bc95a2d to your computer and use it in GitHub Desktop.
QuerySet which returns namedtuples
from itertools import imap
from collections import namedtuple
from django.db.models.query import QuerySet, ValuesQuerySet
class NamedTuplesQuerySet(ValuesQuerySet):
def iterator(self):
# Purge any extra columns that haven't been explicitly asked for
extra_names = self.query.extra_select.keys()
field_names = self.field_names
aggregate_names = self.query.aggregate_select.keys()
names = extra_names + field_names + aggregate_names
tuple_cls = namedtuple('%sTuple' % self.model.__name__, names)
# NOTE: we are not reordering fields here,
# so they can go not in that order as in .namedtuples args
# if extra or aggregates are used.
results_iter = self.query.get_compiler(self.db).results_iter()
return imap(tuple_cls._make, results_iter)
def namedtuples(self, *fields):
return self._clone(klass=NamedTuplesQuerySet, setup=True, _fields=fields)
QuerySet.namedtuples = namedtuples
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment