You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Odoo10新API中如何结合循环使用ORM的create()方法?

修正Odoo 10中创建学年订阅的ORM代码问题

先帮你拆解代码里的核心问题,再给出可运行的修正方案:

代码里的关键错误

  • 误用@api.depends装饰器:这个是给计算字段用来定义依赖触发的,而你是要主动创建记录,完全不适用
  • 模型调用错误:self.env['student_id']是错的——student_id是你的模型字段,不是模型名称,操作学生模型应该用self.env['core.student']
  • 创建目标错误:你要创建的是core.student.ins_year(学年订阅)的记录,但代码里却给学生模型调用create,逻辑完全偏离
  • 遍历逻辑无效:self.env['student_id'].browse()没有传入任何ID,根本拿不到学生数据

修正后的代码示例

假设你要实现「点击按钮为指定学生创建学年订阅」的功能,代码可以这么写:

from odoo import models, fields, api

class InsYear(models.Model):
    _name = 'core.student.ins_year'
    
    student_id = fields.Many2one('core.student', string='Student', required=True)
    year_name = fields.Char(string='Academic Year', required=True)  # 新增学年字段,按需定义
    # 可以添加更多订阅相关字段,比如订阅状态、费用等

    # 按钮触发的方法用@api.multi装饰
    @api.multi
    def create_year_subscription(self):
        # 为当前记录关联的学生创建订阅
        for rec in self:
            self.env['core.student.ins_year'].create({
                'student_id': rec.student_id.id,
                'year_name': '2024-2025',  # 可以换成动态获取的学年值,比如从系统参数读取
                # 其他字段按需填充
            })
        
        # 如果需要批量为所有学生创建订阅(谨慎使用,数据量大时会卡)
        # all_students = self.env['core.student'].search([])
        # for student in all_students:
        #     self.env['core.student.ins_year'].create({
        #         'student_id': student.id,
        #         'year_name': '2024-2025',
        #     })
        return True

额外场景补充

如果想实现「学生创建时自动生成学年订阅」,可以在学生模型里写触发逻辑:

class CoreStudent(models.Model):
    _inherit = 'core.student'
    
    @api.model
    def create(self, vals):
        # 先创建学生记录
        student = super(CoreStudent, self).create(vals)
        # 自动创建学年订阅
        self.env['core.student.ins_year'].create({
            'student_id': student.id,
            'year_name': '2024-2025',
        })
        return student

注意:Odoo的ORM操作里,self.env['模型内部标识']才是正确调用模型的方式,一定要区分模型名称和字段名称,别搞混了。

内容的提问来源于stack exchange,提问作者Bendji benz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:34:58