Hi there,

I quite often find that when using queryset.values() I would like to be 
able to define myself the values of the keys, especially when they span 
models:

e.g.

   my_query_set.values('foo__bar__baz', 'quux', 
'another__long__field__name')

Then I end up with dictionaries with unnecessarily long keys.  What I'd 
like to be able to do is something like:

    my_query_set.values('quux', baz='foo__bar__baz', 
name='another__long__field__name')

Executing this would yield dictionaries of the type:

    {'quux': 2, 'baz': 'type 2', 'name': 'Frobulon'}


I've had a quick look at the ValuesQuerySet class and there seems to be a 
simple enough way to get this feature.  I'm presenting it in the form of a 
new ValuesQuerySet subclass and a monkey patch to the parent QuerySet. 
 It's not unlikely that it will break some things as this is my first peek 
into the QuerySet class.  I'd like to know if this is something that other 
people feel the need for and if it is worth pushing for inclusion of such a 
feature into django.

Cheers,

Arnaud

----------------

from django.db.models.query import QuerySet, ValuesQuerySet


class ValuesDictQuerySet(ValuesQuerySet):

    def iterator(self):
        # Purge any extra columns that haven't been explicitly asked for
        extra_names = list(self.query.extra_select)
        field_map = self.field_map
        field_names = [field_map.get(fname, fname) for fname in 
self.field_names]
        aggregate_names = list(self.query.aggregate_select)

        names = extra_names + field_names + aggregate_names

        for row in self.query.get_compiler(self.db).results_iter():
            yield dict(zip(names, row))

    def _clone(self, klass=None, setup=False, **kwargs):
        c = super(ValuesDictQuerySet, self)._clone(klass, **kwargs)
        c.field_map = self.field_map
        return c


def QuerySet_values_dict(self, *field_list, **field_dict):
    fields = list(field_list)
    fields.extend(field_dict.values())
    field_map = dict(zip(field_dict.values(), field_dict.keys()))
    return self._clone(klass=ValuesDictQuerySet, setup=True, 
_fields=fields, field_map=field_map)


# Now we monkey-patch QuerySet with the new method
QuerySet.values_dict = QuerySet_values_dict

-- 
You received this message because you are subscribed to the Google Groups 
"Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-users+unsubscr...@googlegroups.com.
To post to this group, send email to django-users@googlegroups.com.
Visit this group at http://groups.google.com/group/django-users.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/d4f8d6f0-3723-44d5-991a-9c6b3c13165d%40googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.

Reply via email to