循环遍历模型odoo 11中的对象

Looping through objects in model odoo 11

我想在我的模型 'Artist' 上创建一个函数来将字段 num_albums 更改为他创建的相册的数量。我想我必须使用计算函数并根据艺术家的名字过滤所有专辑。但是,我不知道该怎么做。如果你知道我该怎么做,请帮助我。

这是我的代码:

class Artist(models.Model) :
    _name = 'artist'
    _order = 'name'

    name = fields.Char('Name of Artist')
    age = fields.Integer(string='Age of Artist')
    nationality = fields.Selection([('France', 'France'), ('GB', 'Great Britain'),
    ('USA', 'United States'), ('Russia', 'Russia'), ('China', 'China'),
    ('Other', 'Other')], 'Nationality')
    num_albums = fields.Integer(compute='_get_num_albums', store=False)

    @api.model
    def _get_num_albums(self) :
        **Enter code here**

class Album(models.Model) :
    _name = 'album'
    _order = 'artist.name'

    artist = fields.Many2one('artist', string='Artist')
    name = fields.Char('Name')
    image = fields.Binary('Album Cover')

你可以声明一个 One2many 艺术家与 his/her 专辑的关系,然后只需使用 相册,例如:

class Artist(models.Model):
    _name = 'artist'
    _order = 'name'

    # ...
    albums = fields.One2many(
        comodel_name='album',
        inverse_name='artist',
        string='Albums',
    )
    num_albums = fields.Integer(compute='_get_num_albums', store=False)

    @api.multi
    def _get_num_albums(self):
        for artist in self:
            artist.num_albums = len(artist.albums)

    # ...

或者,在不添加额外字段的情况下,您可以使用 search_count 获取艺术家的专辑数量:

class Artist(models.Model):
    _name = 'artist'
    _order = 'name'

    # ...
    num_albums = fields.Integer(compute='_get_num_albums', store=False)

    @api.multi
    def _get_num_albums(self):
        album_obj = self.env['album']
        for artist in self:
            artist.num_albums = album_obj.search_count([
                ('artist', '=', artist.id),
            ])
    # ...