Reputation: 5946
I'm pull all records from DB and then creating a modified set which is then passed onto the render - this works fine and the added scoring values all all nicely used. Now I would like to sort this modified set but obviously I cannot use the orderby
statement as the score values are not columns in the table. However, the .sort
function doesn't seem to exist, when I try in the shell. Now I could manually create a list, but is there a simpler way and more pythonic way to do this?
mylist = AboutMe.objects.all()
for record in mylist:
record.Score = GenerateScoreFunction(weight_factors, myid, record.id)
return render(request, 'static/list.html', {'list': mylist, 'loggedin': loggedin})
The type of mylist is a Queryset
Upvotes: 0
Views: 76
Reputation: 11228
The most Django way is to see if you can replace the GenerateScoreFunction with annotate and aggregate functions:
https://docs.djangoproject.com/en/1.6/ref/models/querysets/#annotate https://docs.djangoproject.com/en/1.6/ref/models/querysets/#id5
Upvotes: 1
Reputation: 2882
You can use the sorted()
function to return a sorted list based on a given key:
return render(request, 'static/list.html', {'list': sorted(mylist, key=lambda r: r.Score),
'loggedin': loggedin})
Upvotes: 1