2014-03-31 159 views
-1

我需要從子對象獲取所有父對象。我不知道它有多少個父對象,所以我想我需要在這裏以某種方式使用遞歸。獲取所有父'對象'?

所以我有一個對象,可能有或沒有其他的繼承對象。如果它有任何繼承對象,我需要添加對象id到列表中,然後檢查該繼承對象(或多個對象)是否有父母,如果是,則將這些父母ID添加到同一個列表中並檢查他們的父母,等等。當最深的物體沒有任何父母時,它應該停止。

所以我的代碼現在看起來像這樣:

def get_parent_groups(self, cr, uid, ids, grp_id, context=None): 
    res = [] # list for parent ids 
    grp_obj = self.pool.get('res.groups') 
    #grp_id is childs `id` it means same thing as 
    # `parent_grp.id`, only that latter is parent object id. 
    grp = grp_obj.browse(cr, uid, grp_id) 
    if grp.implied_ids: #check if child has any parent ids 
     for parent_grp in grp.implied_ids: 
      res.append(parent_grp.id) #append found parent ids 
    return res 

此代碼僅獲得第一個父對象ID。所以從這裏我想我應該把遞歸和所有其他的父母,但我不能包住我的頭,我應該如何正確地得到它。任何幫助?

P.S. 正如我看到有人問cr, uid是什麼意思,我沒有指定它,因爲我認爲它不涉及這個問題(因爲它確實不是),但要明確這些輸入是OpenERp框架需要的方法:

`cr` - database cursor 
`uid` - current user id 
`ids` - ids of the object 

但正如我所說,這些都不是有問題的關係,我剛剛張貼的工作方法,不會錯過任何東西。

+0

可能重複[得到蟒蛇類的父(S)](http://stackoverflow.com/questions/2611892/ get-python-class-parents) –

+0

不確定這是否是你需要的,但是:'inspect.getmro(cls)'以方法解析順序返回一個包含cls的class cls的基類的元組。文檔:https://docs.python.org/2/library/inspect.html – skamsie

+0

爲什麼選擇投票問題? – Andrius

回答

0

我解決了這個問題這樣的重寫方法。不知道這樣的方式是最好的方式,但它的工作:

def get_parent_groups(self, cr, uid, ids, grp_id, context=None): 
    res = []  
    grp_obj = self.pool.get('res.groups') 
    grp = grp_obj.browse(cr, uid, grp_id) 
    if grp.implied_ids: 
     for parent_grp in grp.implied_ids: 
      res.append(parent_grp.id)    
      if parent_grp.implied_ids: 
       parent_ids = self.get_parent_groups(cr, uid, ids, parent_grp.id) 
       for parent_id in parent_ids: 
        res.append(parent_id) 
    return res 
+0

既然你回答了你自己的問題,你是否也可以做一個演示解釋什麼是所有參數以及你的回報是怎樣的? – skamsie