[Zope] Sorting on 2 or more properties

Casey Duncan casey@zope.com
Mon, 21 Apr 2003 10:31:18 -0400


On Friday 18 April 2003 03:51 pm, Michael Long wrote:
> Hi all,
>=20
> I am passing a list of objects to a zpt and would like to sort them on =
2
> or more of the properties. For example I have a class object with the
> following properties:
>=20
> id
> professor_name
> student_name
> course_number
>=20
> I would like to sort first on the professor_name, then course_number,
> and then finally student_name. I have googled and can only find example=
s
> for sorting on one property at a time.

You could write a general purpose sorting script as follows:

##Script (Python) "multiSort"
##parameters=3Dobjects, *sort_attrs
##title=3DSort a list of objects by one or more of their attributes

results =3D []
for object in objects:
    row =3D [getattr(object, attr) for attr in sort_attrs]
    row.append(object)
    results.append(tuple(row))
results.sort()
return [row[-1] for row in results]

hth,

-Casey