Django Queryset values_list trick

Hi!

I have a queryset looks like this.
toys = Toy.objects.all().order_by(‘price’).values_list(‘id’, ‘price’)

It gives me an iteration of tuples with two values id and price.

[(1, 35), (3, 45), (4, 23), ...]

However, I want to get a dictionary whose key is that id and value is price.

{
   1: 35,
   3: 45, 
   4: 23,
   ...
}

I am curious to know if it can be done in queryset.

Thanks

Not as a queryset function itself, but you can create such a dict by iterating over the queryset.

1 Like