首页 > 解决方案 > Odoo 12:AttributeError:“int”对象没有属性“get”

问题描述

我创建了一个choice_student方法,在该方法中,我在与 res.users 相关的 many2one 字段的默认值中返回了一个 ID,但出现错误:

AttributeError:“int”对象没有属性“get”

这是我的代码:

student_id = fields.Many2one('res.users', 'Etudiant', readonly=True, required=True, default=lambda self: self.choice_student()  )

@api.onchange('projet_terminer_id')
def choice_student(self):
    return self.env['res.users'].sudo().search([ ('id','=', 45)]).id

标签: python-3.xodooodoo-12

解决方案


为了解释为什么会出现这个错误,让我们一步一步开始:

1- 对于默认值使用 decorator api.model,如果你有 id 不要使用 search 使用 browse self.env['some.model'].browse(id),但在你的情况下你根本不需要这个,只需这样做:

    student_id = fields.Many2one('res.users', 'Etudiant', 
                                readonly=True, required=True, 
                                default=45 )

2-onchange也是一种设置默认值的方法,但仅在视图上,因为它们是加载默认值后由客户端触发的第一件事,onchange 方法应该返回或者返回Nonedictionary这就是你得到的原因和错误,AttributeError: 'int' object has no attribute 'get'因为返回的值不是None那么 odoo 试图从字典中获取一些预期值(如:domain, values)但是哎呀你返回了一个 int 而不是字典,这就是为什么 Odoo 会抛出这个错误。

在 onchage 方法中,只需在self记录上直接设置值:

    student_id = fields.Many2one('res.users', 'Etudiant', 
                                readonly=True, required=True,
                                default=45) 

    @api.onchange('projet_terminer_id')
    def choice_student(self):
        self.student_id = self.env['res.users'].sudo().browse(45)

从代码的外观来看,我认为onchange如果您想在student_id更改 projet_terminer_id字段时重置值,则可以保留。


推荐阅读