Skip to content

Instantly share code, notes, and snippets.

@Suor
Created March 18, 2011 15:59
Show Gist options
  • Select an option

  • Save Suor/876324 to your computer and use it in GitHub Desktop.

Select an option

Save Suor/876324 to your computer and use it in GitHub Desktop.

Revisions

  1. Suor revised this gist Mar 18, 2011. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion gistfile1.py
    Original file line number Diff line number Diff line change
    @@ -14,7 +14,7 @@ def iterator(self):
    names = extra_names + field_names + aggregate_names
    tuple_cls = namedtuple('%sTuple' % self.model.__name__, names)

    # NOTE: we are not reordering results here,
    # 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()
  2. Suor revised this gist Mar 18, 2011. 1 changed file with 2 additions and 1 deletion.
    3 changes: 2 additions & 1 deletion gistfile1.py
    Original file line number Diff line number Diff line change
    @@ -17,7 +17,8 @@ def iterator(self):
    # NOTE: we are not reordering results here,
    # so they can go not in that order as in .namedtuples args
    # if extra or aggregates are used.
    return imap(tuple_cls._make, self.query.get_compiler(self.db).results_iter())
    results_iter = self.query.get_compiler(self.db).results_iter()
    return imap(tuple_cls._make, results_iter)


    def namedtuples(self, *fields):
  3. Suor created this gist Mar 18, 2011.
    25 changes: 25 additions & 0 deletions gistfile1.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,25 @@
    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 results here,
    # so they can go not in that order as in .namedtuples args
    # if extra or aggregates are used.
    return imap(tuple_cls._make, self.query.get_compiler(self.db).results_iter())


    def namedtuples(self, *fields):
    return self._clone(klass=NamedTuplesQuerySet, setup=True, _fields=fields)
    QuerySet.namedtuples = namedtuples