#15648: [Feature request] NamedTupleQuerySet
------------------------------------------+---------------------------
 Reporter:  pbagwl                        |         Owner:  nobody
   Status:  new                           |     Milestone:  1.4
Component:  Database layer (models, ORM)  |       Version:  SVN
 Keywords:  namedtuple, tuple, queryset   |  Triage Stage:  Unreviewed
Has patch:  1                             |
------------------------------------------+---------------------------
 Python 2.6 supports named tuples. Information about field names is stored
 in the tuple class, so there's no overhead like in dictionaries.
 I propose to use them in querysets instead of values() / values_list().

 {{{#!python
 qs = Items.objects.filter(...).namedtuples('title', 'amount', 'price')
 for item in qs:
     print item.title, item.amount
     total += item.amount * item.price
 }}}

 Patch:

 {{{#!python
 from itertools import imap
 from collections import namedtuple

 # python 2.5 doesn't support named tuples, so we can use this
 http://code.activestate.com/recipes/500261/

 from django.db.models.query import ValuesQuerySet

 class NamedTuplesQuerySet(ValuesQuerySet):
     def iterator(self):
         # get field names
         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

         # create named tuple class
         tuple_cls = namedtuple('%sTuple' % self.model.__name__, names)

         results_iter = self.query.get_compiler(self.db).results_iter()
         # wrap every string with our named tuple
         return imap(tuple_cls._make, results_iter)
 }}}

 {{{#!python
 from django.db.models.query import QuerySet

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

-- 
Ticket URL: <http://code.djangoproject.com/ticket/15648>
Django <http://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.

-- 
You received this message because you are subscribed to the Google Groups 
"Django updates" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/django-updates?hl=en.

Reply via email to