Skip to content

Instantly share code, notes, and snippets.

@Suor
Created March 18, 2011 15:59
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save Suor/876324 to your computer and use it in GitHub Desktop.
Save Suor/876324 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