由程式指定關聯物件(含反向關聯)

透過TTW的方式維護關聯是最簡單的方式,但有時候我們希望可以由程式自動執行來指定關聯性,本篇提供了這個方法

找不到什麼值得述敘的範例描述,所以直接以程式碼呈現,有需要的讀者請直行體會。

from plone import api
#以下這三個import是本範例主角
from zope import component
from zope.app.intid.interfaces import IIntIds
from z3c.relationfield.relation import RelationValue
#這行取代上一行也行  -->  from z3c.relationfield import RelationValue
from zope.event import notify
from zope.lifecycleevent import ObjectModifiedEvent


class GetRelation(BrowserView):
    def __call__(self):
        catalog = api.portal.get_tool(name='portal_catalog')
        item = catalog(id='ddd')[0].getObject()
        intIds = component.getUtility(IIntIds)
        testObj = catalog(id='abcde')[0].getObject()  #直接取得object
        #以下這段,可以指定'abcde'到關連去,但一開始content裏的relation欄位可能會是nonetype,沒有append()可用
        if hasattr(item, 'append'):
            item.relation.append(RelationValue(intIds.getId(testObj)))
        else:
            item.relation = [RelationValue(intIds.getId(testObj))] #對應到RelationList,使用[]
        notify(ObjectModifiedEvent(getSelfObject))   #通知系統,建立反向連結關係

        item.reindexObject()
        return #打完收工

原文出處:無,這篇是自行研究出來的,有找到文件的朋友,也可以幫忙補上