Odoo如何覆盖默认功能新API

时间:2017-07-10 12:01:21

标签: python-2.7 inheritance openerp odoo-9

我正在尝试覆盖类消息方法 此示例 def _get_default_author(self)by this example

原始模型:

class Message(models.Model):
    _name = 'mail.message'
    _inherit = ['ir.needaction_mixin']

     @api.model
     def _get_default_author(self):
         return self.env.user.partner_id

     author_id = fields.Many2one(
             'res.partner', 'Author', select=1,
             ondelete='set null', default=_get_default_author,
             help="Author of the message. If not set, email_from may hold an email address that did not match any partner.")

继承的模型:

class MyClass(models.Model):
    _name = 'my.class'
    _inherit = ['mail.thread', 'ir.needaction_mixin']

    @api.model
    def _get_default_author(self):
        new = self.env['res.users'].search([('id', '=', '1')])
        return new.partner_id

    author_id = fields.Many2one(default=_get_default_author)

但我收到了一个错误:

File "/opt/odoo/openerp/models.py", line 4113, in create
    vals = self._add_missing_default_values(vals)
  File "/opt/odoo/openerp/api.py", line 236, in wrapper
    return new_api(self, *args, **kwargs)
  File "/opt/odoo/openerp/api.py", line 478, in new_api
    result = method(self._model, cr, uid, *args, **old_kwargs)
  File "/opt/odoo/openerp/models.py", line 1776, in _add_missing_default_values
    defaults = self.default_get(cr, uid, list(missing_defaults), context)
  File "/opt/odoo/openerp/api.py", line 238, in wrapper
    return old_api(self, *args, **kwargs)
  File "/opt/odoo/openerp/api.py", line 342, in old_api
    result = method(recs, *args, **kwargs)
  File "/opt/odoo/openerp/models.py", line 1336, in default_get
    defaults = self._convert_to_cache(defaults, validate=False)
  File "/opt/odoo/openerp/models.py", line 5454, in _convert_to_cache
    for name, value in values.iteritems()
  File "/opt/odoo/openerp/models.py", line 5455, in <dictcomp>
    if name in fields
  File "/opt/odoo/openerp/fields.py", line 1655, in convert_to_cache
    raise ValueError("Wrong value for %s: %r" % (self, value))
ValueError: Wrong value for my.class.author_id: res.partner(3,)

我做错了什么?也许有另一种方法来覆盖默认功能?

更新: 仅仅为了测试我对核心类Message(models.Model)进行了相同的更改。一切都很好。据我所知,问题出在我的代码上。也许我把它覆盖错了..

1 个答案:

答案 0 :(得分:3)

您不是在覆盖或扩展mail.message,而是创建自己的模型my.class。要扩展或覆盖Odoo模型,您只需使用_inherit类属性:

class MyClass(models.Model):
    _inherit = 'mail.message'
    _name = 'mail.message'  # optional!

    @api.model
    def _get_default_author(self):
        new = self.env['res.users'].search([('id', '=', '1')])
        return new.partner_id

    author_id = fields.Many2one(default=_get_default_author)

现在给你的错误。您正在使用字段my.class创建自己的模型author_id。这个字段是一个很多的关系字段,它总是需要一个comodel来获得一个关系。通过思考“我将覆盖另一个模型的默认函数”,你当然没有填充comodel_name参数,因为在重写时,这是不需要的。

但你不是压倒一切。所以Odoo用object()填充comodel_name。您的默认方法是返回res.partner条记录,但Odoo需要object条记录。

因此,错误只是继承/覆盖现有Odoo模型的错误尝试的后果。