[Tutor] sorting objects in lists by 2 attr

Philippe Niquille philippe at niquille.com
Mon Jul 23 19:09:47 CEST 2007


Hi


I have a hard time sorting an object list. Perhaps this is kind of a noob
question, but I would very much appreciate any help!


Using django I get a QuerySet of Score objects which are sorted by the
actual score, the actual score divided by the max. possible score (so
sorting by two db fields).

I then need to loop through that queryset and sum up all the score objects
which belong to the same user into one Score objects. This works (see code
below).


The problem I now have, is that I lost the sorting order, as described
above. How would I resort it with a python algortithm instead of SQL?


 scores = Score.objects.order_by('score', 'score2','owner') # filter by
course, MC !!

 # loop through scores to regroup by user

newscore = []

for s in scores:

i = False

# loop through new object container and check for existant user index, add
scores if existant

for ns in newscore:

if s.owner == ns.owner:

ns.score = int(ns.score) + int(s.score)

ns.maxscore = int(ns.maxscore) + int(s.maxscore)

i = True

# otherwise append new user index object, work with it later, perhaps (if
more user objects exist)

if i == False:

newscore.append(s)


-----------------


I did fiddle around with .sort() but didn't get any useful results (and it
would only sort by one object..).


class CmpAttr:

def __init__(self, attr):

self.attr = attr

def __call__(self, x, y):

return cmp(getattr(x, self.attr), getattr(y, self.attr))


newscore.sort(CmpAttr("score"))



ps. could it be, that this maillist is blocking some e-mail addresses?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20070723/4fb21fb2/attachment.html 


More information about the Tutor mailing list