Reputation: 2457
I'm trying to sort a list of dictionary through the use of values() of a querySet.
I find the list of dictionaries through:
set_of_pk_values = user_chartConfigurationData.objects.filter(username_chartNum_id = activeTab+"_"+username).values()
Since the data is sent to a jQuery DataTables. The user can click on each of the column to sort the data.
Hence, I find the "key" through order[0][column] from GET
keyOrder = set_of_pk_values[0].keys()[int(order_0_iColumn)]
keyOrder is now the key that I want to sort.
However, when I tried to use sorted with a operator:
set_of_pk_values = sorted(set_of_pk_values, key=operator.attrgetter(keyOrder))
It returns an error message: 'dict' object has no attribute 'blockName', which is actually one of the attribute of the dictionary, if you would call set_of_pk_values[0]['blockName']
Upvotes: 0
Views: 1334
Reputation: 37364
To get a value from a dict by key, use operator.itemgetter
rather than operator.attrgetter
. Though it might be worthwhile to pull the sort field out before running your values
query and have the database do the sort instead.
Upvotes: 3