Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Return list of dicts for values_list?

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)
like image 239
mpen Avatar asked Jun 19 '11 21:06

mpen


1 Answers

Why not just use values() in the first place?

like image 68
Ignacio Vazquez-Abrams Avatar answered Oct 17 '22 16:10

Ignacio Vazquez-Abrams