quick search:

Auto-generate Ids for ZClass Instances

Submitted by: cduncan
Last Edited: 2001-08-01

Category: Python(External Method)

Average rating is: 3.0 out of 5 (1 ratings)

It can often be convenient to auto-generate ids for ZClass
instances. Using this short external method and a small
modification to the ZClass constructor, this is fairly easy to do.

You can use this single external method to generate ids
for as many ZClasses as desired.

Source (Text):
External method code:

def get_next_id(ZClass, Folder=None):
    """Generate a unique sequencial id for the ZClass"""
    ZClass.next_id = getattr(ZClass, 'next_id', 0) + 1
    id = ZClass.getId() + '_' + ZClass.next_id
    if Folder and id in Folder.objectIds():
        id = get_next_id(ZClass, Folder)
    return id

Place the above code in a ".py" file in your Zope extensions
directory. Then create an external method "get_next_id"
inside Zope in the Root Folder (!) that exposes the method
function. Change the following line in the constructor
DTML method of your ZClass (ZClass_add):

<dtml-with "ZClass.createInObjectManager(REQUEST['id'], REQUEST)">


<dtml-with "ZClass.createInObjectManager(get_next_id(ZClass, this()), REQUEST)">

Substitute the actual id of your ZClass for "ZClass" in the above line.

The code works by creating an incrementing an attribute of the
ZClass named next_id. It then creates an id by concatenating
the id of the ZClass with the next_id value.

If a value is passed for Folder (which should be the folder the
instance is being created in), then it checks to make sure the id
is not already in the folder. If it is, it generates new ids until an
unused one is found.

The change to the ZClass constructor method then uses the
above method to get an id instead of getting it from REQUEST.
You should also modify the constructor form (ZClass_addForm)
to remove the id input box which is no longer needed.


by nrp - 2001-08-01
I had to change line 4 of the external code to read
    id = "%s_%s" % (ZClass.getId(), ZClass.next_id)