调用其他模型的create方法

时间:2017-09-14 07:18:50

标签: python-2.7 openerp odoo-10

我有两个模型,我需要在survey.page模型中创建survey.survey模型中的记录(点击保存按钮)。我试过的方法不起作用。有什么建议我能做到吗?

class Survey(models.Model):
_name = 'survey.survey'
   @api.multi
    def my_func(self):
        last_id = self.env['survey.survey'].search([])[-1].id
        vals = {'title': 'Page 1', 'survey_id': last_id}
        other_object = self.env['survey.page']
        return other_object.create(vals)


class SurveyPage(models.Model):
    _name = 'survey.page'

    title = fields.Char('Page Title', required=True, translate=True)
    survey_id = fields.Many2one('survey.survey', string='Survey', ondelete='cascade', required=True)

1 个答案:

答案 0 :(得分:2)

您可以使用create模型的覆盖survey.survey方法来执行此操作。 试试Blow代码:

class Survey(models.Model):
    _name = 'survey.survey'
    @api.multi
    def my_func(self):
        self.ensure_one()
        vals = {'title': 'Page 1', 'survey_id': self.id}
        other_object = self.env['survey.page']
        return other_object.create(vals)

    @api.model
    def create(self, vals):
       res = super(Survey, self).create(vals)
       res.my_func()
       return res

class SurveyPage(models.Model):
    _name = 'survey.page'

    title = fields.Char('Page Title', required=True, translate=True)
    survey_id = fields.Many2one('survey.survey', string='Survey', ondelete='cascade', required=True)