【问题标题】:Odoo 9 context value missing in override method覆盖方法中缺少 Odoo 9 上下文值
【发布时间】:2017-06-28 14:45:49
【问题描述】:

在 odoo9 中,我重写了 search_read 方法。超级方法工作正常。使用返回的数据,我想制作一个过滤器,该过滤器位于上下文中,该值是在单击来自视图的按钮时分配的。

    <button name="status_instalacion" string="Instalación" type="action" icon="fa-wrench  fa-2x"  context="{'stage_id' : 1, 'current_id': active_id}"/> 

当我在 search_read 方法中查询上下文时出现问题。它存在但没有我放置的值

点击按钮的上下文:

self._context {u'lang': u'en_US', u'stage_id': 1, u'tz': False, u'uid': 1, u'current_id': 40, u'tipo_validacion': u'Sistemas Cr\xedticos ', u'sistema_critico': u'AGUA'}

stage_id 是我想要的值

read_search 上的上下文:

self._context {u'lang': u'en_US', u'bin_size': True, u'tipo_validacion': u'Sistemas Cr\xedticos', u'tz': False, u'uid': 1, u'active_test': False, u'sistema_critico': u'AGUA'}

如您所见,缺少“stage_id”值

也尝试将值分配给类的属性,但值永远不会改变它始终是初始值。

from logging import getLogger
from openerp import api, fields, models

_logger = getLogger(__name__)


class MgmtsystemSistemasEquipos(models.Model):
    """ Equipos."""

    _name = 'mgmtsystem.sistemas.equipos'
    dmy = 99  # ---> this value never changes

    def dummy(self):       # ---> tried calling a function. not work
        return self.dmy

    def set_dummy(self, id):      # ----> set the value
        self.dmy = id or self.dmy

    codigo = fields.Char(
        string=u'Código',
        help=u"Código equipo",
        required=True,
        size=30)
    name = fields.Char(
        string=u'Nombre equipo',
        required=True,
        readonly=False,
        index=True,
        help="Nombre corto equipo",
        size=30)
    stage_id = fields.Many2one(
        'mgmtsystem.action.stage',
        'Fase',
        default=_default_stage,
        readonly=True)


    @api.multi
    def status_instalacion(self):

        import pudb
        pu.db

        # save value to variable dmy to retrieve later
        id = self._context.get('stage_id')
        self.set_dummy(id)



    @api.model
    def search_read(
            self, domain=None, fields=None, offset=0,
            limit=None, order=None):

        import pudb
        pu.db

        # here the variable allways has the original value (99)
        current_stage_id = self.dmy
        current_stage_id = self.dummy()
        current_stage_id = getattr(self, dmy)


        res = super(MgmtsystemSistemasEquipos, self).search_read(
            domain, fields, offset, limit, order)

        current_id = res[0]['id']

        valid_protocols_ids = self._get_ids(
            current_stage_id, current_id,
            'mgmtsystem_equipos_protocolos',
            'mgmtsystem_equipos_protocolos_rel',
            'protocolo_id')

        # # remove ids
        res[0]['protocolos_ids'] = valid_protocols_ids
        res[0]['informes_ids'] = valid_informes_ids
        res[0]['anexos_ids'] = valid_anexos_ids

        return res


    # @api.multi
    def _get_ids(self, current_stage_id, current_id, model, model_rel, field_rel):

        import pudb
        pu.db

        # in this method the value of the variable is allways the original
        current_stage_id = self.dummy()

        sql = """ select a.id from
            %s as a
            join %s as b
            on a.id = b.%s where b.equipo_id = %s
            and a.stage_id = %s; """ % (model, model_rel, field_rel,
                                        current_id, current_stage_id)

        import psycopg2

        try:
            self.env.cr.execute(sql)
        except psycopg2.ProgrammingError, ex:
            message = 'Error trying to download data from server. \n {0} \n {1}'.format(ex.pgerror, sql)
            _logger.info(message)
            return False

        rows = self.env.cr.fetchall()
        list_of_ids = []

        for row in rows:
            list_of_ids.append(row[0])

        return list_of_ids

我对Python不是很了解,这就是我对如何读取变量值的误解的原因。

但话说回来,为什么在 search_read 方法中修改了上下文?

谢谢。

【问题讨论】:

    标签: openerp odoo-9


    【解决方案1】:

    您应该尝试关注。

    @api.model
    def search_read(self, domain=None, fields=None, offset=0, limit=None, order=None):
    
        import pudb
        pu.db
    
        # Here you need to get the value from the context.
        current_stage_id = self._context.get('stage_id', getattr(self, dmy))
    
        res = super(MgmtsystemSistemasEquipos, self).search_read(domain=domain, fields=fields, offset=offset, limit=limit, order=order)
    
        current_id = res[0]['id']
    
        valid_protocols_ids = self._get_ids(
            current_stage_id, current_id,
            'mgmtsystem_equipos_protocolos',
            'mgmtsystem_equipos_protocolos_rel',
            'protocolo_id')
    
        # # remove ids
        res[0]['protocolos_ids'] = valid_protocols_ids
        res[0]['informes_ids'] = valid_informes_ids
        res[0]['anexos_ids'] = valid_anexos_ids
    
        return res
    

    在您的代码中,这些行将不起作用,因为 self 中没有可用的记录集(正确的行为 search_read 必须具有 @api.model 装饰器)。

        # here the variable allways has the original value (99)
        current_stage_id = self.dmy
        current_stage_id = self.dummy()
        current_stage_id = getattr(self, dmy)
    

    所以只需删除这些和行并应用一些其他逻辑来获取数据。

    【讨论】:

    • Empiro,谢谢,但没用。给出消息:AttributeError:'mgmtsystem.sistemas.equipos'对象没有属性'dmy'我注意到模型有对象>>> self mgmtsystem.sistemas.equipos(40,)在调用search_read方法之前但在内部search_read 方法,对象变为 >>> self mgmtsystem.sistemas.equipos() 就像是主模型的一个空副本
    • 只需将getattr(self, dmy) 替换为默认值,如current_stage_id = self._context.get('stage_id', 99)
    • 你得到他的错误的原因是@api.model装饰器将有空记录集,所以自我中没有对象。所以 self 中没有任何可用的属性。
    • 尝试删除装饰器,与其他装饰器一起但都给我错误,我唯一可以使用的装饰器是@api.model。如果你不介意你能解释一下如何调用这个方法。谢谢。
    • 嗨,解决了它通过临时表(models.TransientModel)传递值,在按钮中单击`model_obj = self.env['tmp.stage'] stage_id = self._context.get('stage_id' ) obj = model_obj.create({'stage_id': stage_id, 'used': False}) ` search_read 中的下一个读取值` uid = self._context.get('uid') Model = self.env['tmp.stage '] 尝试: res_model = Model.search([ ('create_uid', '=', uid), ('used', '=', False) ])[-1] 除了 IndexError: _logger.info(IndexError.message ) ` 谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-09
    • 1970-01-01
    • 2015-12-07
    • 2018-06-25
    • 2020-05-05
    • 1970-01-01
    相关资源
    最近更新 更多