Django:返回values_list的dicts列表?

时间:2021-08-28 21:27:58

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('city1__id','city1__name')我可以写:

.values_list({'id':'city1__id','name':'city1__name'})

And it would return me back a lists of dicts, like

它会让我回到一个dicts列表,比如

[{'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:

我正在浏览Django源代码,但我不知道如何覆盖它:

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)

1 个解决方案

#1


19  

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

为什么不首先使用values()?

#1


19  

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

为什么不首先使用values()?