添加依赖后仍遇KeyError:Odoo CRM与保险模块关联升级报错
问题原因分析及解决方案
原因分析
- 模块加载顺序冲突:直接在原生CRM模块的
crm.lead模型中添加One2many字段insurance_ids,关联Insurance模块的insurance.details模型的crm_lead_ref字段。但Insurance模块依赖CRM模块,加载时CRM模块会先初始化,此时Insurance模块的insurance.details模型还未加载,导致CRM模块找不到反向字段crm_lead_ref,触发KeyError。 - 核心模块修改违规:直接修改Odoo原生CRM模块违反了模块扩展规范,不仅会引发依赖加载问题,还会导致后续官方模块升级时的冲突。
- 上下文键不匹配:
create_insurance_action方法中上下文传递的是default_lead_id,但Insurance模块的create方法中获取的是default_crm_lead_ref,两者不匹配,会导致创建保险记录时无法自动关联Lead。
解决方案
推荐方案:创建独立扩展模块实现功能
不要修改原生CRM模块,新建一个专属扩展模块(如crm_insurance_extension),依赖CRM和Insurance Management模块,通过继承方式扩展功能:
1. 扩展模块结构
crm_insurance_extension/ ├── __manifest__.py ├── models/ │ └── crm_lead.py └── views/ └── crm_lead_views.xml
2. 配置__manifest__.py
{ 'name': 'CRM Insurance Extension', 'version': '16.0.1.0.0', 'summary': '关联CRM线索与保险记录', 'depends': ['crm', 'insurance_management'], 'data': [ 'views/crm_lead_views.xml', ], 'installable': True, 'auto_install': False, 'license': 'AGPL-3', }
3. 扩展crm.lead模型(models/crm_lead.py)
from odoo import models, fields class Lead(models.Model): _inherit = "crm.lead" insurance_ids = fields.One2many('insurance.details', 'crm_lead_ref', string='保险记录') def create_insurance_action(self): return { 'name': '创建保险记录', 'type': 'ir.actions.act_window', 'res_model': 'insurance.details', 'view_mode': 'form', 'target': 'new', 'context': { 'default_partner_id': self.partner_id.id, 'default_crm_lead_ref': self.id }, 'views': [(False, 'form')], 'view_id': False, }
4. 修复Insurance模块的上下文匹配问题(insurance_details.py)
确保create方法中获取的上下文键和扩展模块传递的一致:
from odoo import models, fields class InsuranceDetails(models.Model): _name = 'insurance.details' _inherit = ["mail.thread"] crm_lead_ref = fields.Many2one('crm.lead', string='CRM线索关联', help='关联创建此保险记录的CRM线索', required=True, store=True) def create(self, vals): if vals.get('name', 'New') == 'New': vals['name'] = self.env['ir.sequence'].next_by_code('insurance.details') or 'New' crm_lead_ref = self.env.context.get('default_crm_lead_ref') if crm_lead_ref: vals['crm_lead_ref'] = crm_lead_ref return super(InsuranceDetails, self).create(vals)
5. 完善Lead视图(views/crm_lead_views.xml)
给tree视图添加显示字段,避免空列表:
<odoo> <record id="view_crm_lead_form_inherit" model="ir.ui.view"> <field name="name">crm.lead.form.inherit.insurance</field> <field name="model">crm.lead</field> <field name="inherit_id" ref="crm.view_crm_lead_form"/> <field name="arch" type="xml"> <xpath expr="//page[@name='notes']" position="after"> <page string="保险记录"> <field name="insurance_ids"> <tree> <field name="name"/> <field name="partner_id"/> <!-- 添加其他需要显示的字段 --> </tree> </field> <button name="create_insurance_action" string="创建保险记录" type="object" class="oe_highlight"/> </page> </xpath> </field> </record> </odoo>
额外注意事项
- 移除
insurance_ids字段的required=True属性:新建CRM线索时无保险记录,强制必填会导致线索无法创建。 - 卸载之前修改过的CRM模块,恢复原生状态,再安装新的扩展模块和Insurance模块。
内容的提问来源于stack exchange,提问作者Kamil Wolski
相关产品推荐
相关产品推荐

