在odoo模型11中遍历对象

时间:2018-10-11 18:18:44

标签: python odoo odoo-10 odoo-9 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')

1 个答案:

答案 0 :(得分:1)

您可以声明一个 One2many 从艺术家到他/她的专辑的关系,然后简单地使用 相册,例如:

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),
            ])
    # ...