Fixing items with a duplicate UID

I had some content items that weren't indexed in the UID index, because a mistake in a migration script had assigned them UIDs that were already used by another item. I used this script to find them and assign them new UIDs.

from plone import api
from zope.component.hooks import setSite
import transaction
import uuid

setSite(app.Plone)
catalog = api.portal.get_tool("portal_catalog")
uid_idx = catalog.Indexes["UID"]
uid_rids = set(uid_idx._index.values())
for brain in catalog.getAllBrains():
    if brain.getRID() not in uid_rids:
        # This item can not be found using the UID index.
        print(brain.getPath())
        obj = brain._unrestrictedGetObject()
        # Assign a new random UID
        setattr(obj, "_plone.uuid", uuid.uuid4().hex)
        # Make sure the UUIDIndex doesn't mistakenly think it has this object indexed,
        # otherwise reindexing will remove the wrong doc from the index!
        del uid_idx._unindex[brain.getRID()]
        # Index the new UID
        obj.reindexObject(idxs=["UID"])

transaction.commit()
6 Likes