Django: Return list of dicts for values_list?

14,045

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

Share:
14,045
mpen
Author by

mpen

Updated on June 04, 2022

Comments

  • mpen
    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
    mpen almost 13 years
    I got used to using values_list, I forgot what values actually did...haha. But still, I'd prefer to rename the fields. city1__name doesn't make a very nice key.
  • Ignacio Vazquez-Abrams
    Ignacio Vazquez-Abrams almost 13 years
    Remapping is the easy part though, via a genex in dict().
  • mpen
    mpen almost 13 years
    Eh? Then I have to create another dict mapping {'city1__name':'name'} and do some crazy logic to convert it....that seems more verbose than using values_list and passing it through [dict(zip(keys,values)) for values in values_list]
  • Marc
    Marc over 3 years
    too simple, does not compute.