@classmethod
    def delete_if_unreferenced(cls, model_object, publish=True, dispatch_trigger=True):
        # Found in the innards of mongoengine.
        # e.g. {'pk': ObjectId('5609e91832ed356d04a93cc0')}
        delete_query = model_object._object_key
        delete_query['ref_count__lte'] = 0
        cls._get_impl().delete_by_query(**delete_query)

        # Since delete_by_query cannot tell if teh delete actually happened check with a get call
        # if the trigger was deleted. Unfortuantely, this opens up to races on delete.
        confirmed_delete = False
        try:
            cls.get_by_id(model_object.id)
        except __HOLE__:
            confirmed_delete = True

        # Publish internal event on the message bus
        if confirmed_delete and publish:
            try:
                cls.publish_delete(model_object)
            except Exception:
                LOG.exception('Publish failed.')

        # Dispatch trigger
        if confirmed_delete and dispatch_trigger:
            try:
                cls.dispatch_delete_trigger(model_object)
            except Exception:
                LOG.exception('Trigger dispatch failed.')

        return model_object
dataset/ETHPy150Open StackStorm/st2/st2common/st2common/persistence/trigger.py/Trigger.delete_if_unreferenced