2015-04-02 97 views
1

有沒有辦法從父模型類對象訪問子模型類對象,或者現在父類模型類對象具有哪個子模型類?從Odoo8中的父模型類對象訪問子模型類

這裏是我的模型類:

class Content(models.Model): 
    _name = 'content' 

    title = fields.Char(string='Title', required=False) 
    summary = fields.Char(string='Summary', required=False) 
    description = fields.Char(string='Description', required=False) 


class Video(models.Model): 
    _name = 'video' 
    _inherits = {'content': 'content_id'} 

    duration = fields.Float(string='Duration', required=False) 


class Image(models.Model): 
    _name = 'image' 
    _inherits = {'content': 'content_id'} 

    width = fields.Float(string='Width', required=False) 
    height = fields.Float(string='Height', required=False) 

如果我有「內容」類的一個對象說「內容1」有子對象「圖像1」,在那裏訪問的方式「圖像1」對象來自「content1」對象還是現在該類型的「content1」是「Image」?

內容將來可能有很多子類,所以我不想查詢所有的子類。

回答

1

在Odoo您可以前往雙向但是你的模型應該配置這樣,

class Content(models.Model): 
    _name = 'content' 
    _rec_name='title' 

    title = fields.Char(string='Title', required=False) 
    summary = fields.Char(string='Summary', required=False) 
    description = fields.Char(string='Description', required=False) 
    video_ids : fields.One2many('video','content_id','Video') 
    image_ids : fields.One2many('image','content_id','Video') 

class Video(models.Model): 
    _name = 'video' 
    _inherit = 'content' 

    duration = fields.Float(string='Duration', required=False) 
    content_id = fields.Many2one('content','Content') 

class Image(models.Model): 
    _name = 'image' 
    _inherit = 'content' 

    width = fields.Float(string='Width', required=False) 
    height = fields.Float(string='Height', required=False) 
    content_id = fields.Many2one('content','Content') 

而且你可以通過調用以這種方式訪問​​子類的功能。

for video in content1.video_ids: 
    ## you can access properties of child classes like... video.duration 

for image in content1.image_ids: 
    print image.width 

同樣,你可以用同樣的方法調用子類的方法。

如果您的目標是做其他事情,請使用示例進行指定。

+0

其實我想要避免的是每次創建一個新的子類時修改父類,即在父類中添加「_ids = fields.One2many()」字段。如果我不能從父類的對象訪問子類的對象,只需要知道這個父對象屬於哪個子類就足夠了,這樣我就不必查詢所有的子類而只需要查詢一個子類。所以我正在尋找一種解決方案,比如我在父類中添加了一個類似「child_table」的字段,並且每個子類都使用其「_name」屬性填充此父字段。用這種方式,我覺得它會容易得多。 – 2015-04-03 07:49:21

+1

以適當的方式維護關係總是明智的,因此您將獲得oops允許的所有自由。 – 2015-04-03 09:39:12