Odoo V13 Discuss模块发消息报IndexError: tuple index out of range问题咨询
报错根因
触发IndexError的核心原因是代码直接对空记录集取下标:
channel_partner_id.partner_id.user_ids是合作伙伴关联的系统用户列表,Odoo中很多合作伙伴(比如外部联系人、客户档案)并不会绑定系统用户账号,此时该记录集为空,直接调用[0]取第一个元素就会触发索引越界。- 同时你的代码还存在多个潜在隐患,会导致后续运行报错:
- 消息子类型搜索未加限制,
ilike匹配名称可能返回多条结果,直接取.id会报错 - 日志对象名不一致:定义的变量是
logger,后续调用却用了_logger,会触发未定义变量异常 __name__拼写错误,缺少末尾下划线- 类名
MailThred为拼写错误,正确应为MailThread(不影响运行但不符合规范)
- 消息子类型搜索未加限制,
修复后代码
import logging from odoo import models, api from odoo.exceptions import AccessDenied, UserError # 修复__name__拼写错误 logger = logging.getLogger(__name__) # 修复类名拼写错误 class MailThread(models.AbstractModel): _inherit = "mail.thread" @api.returns('mail.message', lambda value: value.id) def message_post(self, *, body='', subject=None, message_type='notification', email_from=None, author_id=None, parent_id=False, subtype_id=False, subtype=None, partner_ids=None, channel_ids=None, attachments=None, attachment_ids=None, add_sign=True, record_name=False, **kwargs): res = super(MailThread, self).message_post(body=body, subject=subject, message_type=message_type, email_from=email_from, author_id=author_id, parent_id=parent_id, subtype_id=subtype_id, subtype=subtype, partner_ids=partner_ids, channel_ids=channel_ids, attachments=attachments, attachment_ids=attachment_ids, add_sign=add_sign, record_name=record_name, **kwargs) # 搜索子类型加limit=1,避免返回多条结果,先判断是否存在再后续操作 message_subtype_id = self.env['mail.message.subtype'].sudo().search([('name', 'ilike', 'Discussions')], limit=1) if not message_subtype_id: return res if res.message_type == 'comment' and res.subtype_id.id == message_subtype_id.id: for each in res.channel_ids: for channel_partner_id in each.channel_last_seen_partner_ids: if channel_partner_id.partner_id.id != res.author_id.id: from . import FCMManager as fcm # 先取第一条用户,为空就跳过 target_user = channel_partner_id.partner_id.user_ids[:1] if not target_user or not target_user.firebase_id: continue registration_id = target_user.firebase_id try: tokens = [str(registration_id)] message_title = "ControlE@ERP - CHAT" message_body = res.body fcm.sendPush(message_title, message_body, tokens) # 统一日志变量名 logger.info('ControlE@ERP Alert- NEW CHAT MESSAGE SENT') except Exception as e: logger.info('not sent') return res
内容的提问来源于stack exchange,提问作者IT Spark
相关产品推荐
相关产品推荐

