Django: Return list of dicts for values_list?
14,045
Why not just use values()
in the first place?
Comments
-
mpen almost 2 years
I've got this query:
cities = ShippingPrice.objects.filter(city1__name__icontains=request.REQUEST.get('city','')).values_list('city1__id','city1__name').order_by('city1__name').distinct()
Which returns a list of lists. It would be nice instead of doing
.values_list('city1__id','city1__name')
I could write:.values_list({'id':'city1__id','name':'city1__name'})
And it would return me back a lists of dicts, like
[{'id':4135,'name':'Seattle'},{'id':4154,'name':'Vancouver'}]
Are there any existing methods to do that?
I'm looking through the Django source code, but I'd have no idea how to override this:
def values_list(self, *fields, **kwargs): flat = kwargs.pop('flat', False) if kwargs: raise TypeError('Unexpected keyword arguments to values_list: %s' % (kwargs.keys(),)) if flat and len(fields) > 1: raise TypeError("'flat' is not valid when values_list is called with more than one field.") return self._clone(klass=ValuesListQuerySet, setup=True, flat=flat, _fields=fields)
-
mpen almost 13 yearsI got used to using
values_list
, I forgot whatvalues
actually did...haha. But still, I'd prefer to rename the fields.city1__name
doesn't make a very nice key. -
Ignacio Vazquez-Abrams almost 13 yearsRemapping is the easy part though, via a genex in
dict()
. -
mpen almost 13 yearsEh? Then I have to create another dict mapping
{'city1__name':'name'}
and do some crazy logic to convert it....that seems more verbose than usingvalues_list
and passing it through[dict(zip(keys,values)) for values in values_list]
-
Marc over 3 yearstoo simple, does not compute.