[Zope] sorting ids in python

Peter Bengtsson peter at fry-it.com
Thu Dec 11 06:28:00 EST 2008


2008/12/11 robert rottermann <robert at redcor.ch>:
> Garry Saddington schrieb:
>> On Tuesday 09 December 2008 03:15, Andreas Jung wrote:
>>> On 08.12.2008 21:11 Uhr, robert rottermann wrote:
>>>> Garry Saddington schrieb:
>>>>> Can anyone help me sort the following by id in a python script?
>>>>>
>>>>> for object in context.objectValues(['Folder', 'DTML
>>>>> Document','ZipFolder','File','Image']):
>>>> objs=context.objectValues(['Folder',
>>>> 'DTMLDocument','ZipFolder','File','Image']) objs.sort()
>>>> for o in objs:
>>>>   ..
>>> huh? Afaik there is no sort order defined on a per-object basis.
>>>
>> This is my final working solution:
>>
>> ids = context.objectIds(['Folder', 'DTMLDocument','ZipFolder','File','Image'])
>> ids.sort()
>> for object in ids:
>>     object=context.restrictedTraverse(object)
>>     path=object.absolute_url()
>> ...........................
> I think you can have it a little bit easier:
> use context.objectItems instead of objectIds
> context.objectItems returns (id, object) tuples.
>
> so your solution wold be:
> objs = context.objectItems(['Folder', 'DTMLDocument','ZipFolder','File','Image'])
> objs.sort()
> for id, object in objs:
>     path=object.absolute_url()
> robert

Personally I prefer to always use objectValues(). Sorting isn't
objectXXX()'s problem. It's something you do in your view.
objs = list(self.objectValues())
objs.sort(lambda x,y: cmp(x.id, y.id))

It's only a matter of time until you need something more "advanced"
and then you shouldn't
have to change how you use the objectXXX() iterator. E.g.:
objs.sort(lambda x,y: cmp(x.title_or_id().lower(), y.title_or_id().lower()))


-- 
Peter Bengtsson,
work www.fry-it.com
home www.peterbe.com
hobby www.issuetrackerproduct.com


More information about the Zope mailing list