Search code examples
odooopenerp-8odoo-8

Access child model class from parent model class object in Odoo8


Is there a way to access child model class object from parent model class object or now what child model class does this parent model class object has?

Here are my model classes:

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)

If I have an object of "Content" class say "content1" that has a child object "image1", is there a way to access that "image1" object from "content1" object or now that type of "content1" is "Image"?

Content can have many child classes in future so I don't want to query all the child classes.


Solution

  • In Odoo you can travel bi-direction but your models should have configured like that,

    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')
    

    And you can access functionality of child classes by calling in this way.

    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
    

    Similarly you can call the method of child classes the same way.

    If your aim is to do something else then specify it with example.