Odoo自定义模块调用res.partner.create创建联系人报错或生成空记录求助
问题排查与解决方案
核心问题原因
- 向导调用逻辑错误:原代码中
ConfirmWizard的action_confirm方法直接通过self.env['customer.regist'].action_done()调用业务方法,此时拿到的customer.regist是空记录集,self.full_name为空,要么触发else返回False,要么创建partner时name取值为False,导致报错或空name记录。 - city字段赋值错误:
res.partner的city字段为Char类型存储城市名称,原代码直接传入city_id.id(关联城市表的主键数字),属于赋值类型不匹配。 - _rec_name配置错误:
customer.regist模型配置_rec_name='name',但模型中没有name字段,只有full_name字段,会导致列表视图等场景显示异常。
修正方案
1. 修正瞬态向导逻辑
首先给向导增加关联业务记录的字段,调用对应记录的业务方法:
class ConfirmWizard(models.TransientModel): _name='confirm.wizard' # 新增关联待处理的客户注册记录字段 regist_id = fields.Many2one('customer.regist', string='待审核注册记录', required=True) def action_confirm(self): # 调用指定注册记录的审核方法 return self.regist_id.action_done()
同时需要修改触发向导的窗口动作XML配置,在action的context参数中添加默认值:
<field name="context">{'default_regist_id': active_id}</field>
2. 修正customer.regist模型逻辑
修正_rec_name配置,优化action_done方法的兼容性和校验:
from odoo.exceptions import ValidationError class CustomerRegist(models.Model): _name = "customer.regist" _description = 'Customer Registration' _inherit = ['mail.thread', 'mail.activity.mixin'] _rec_name='full_name' # 修正为实际存在的姓名字段 _order='phone' def action_done(self): # 支持批量处理多条记录 for record in self: if not record.full_name: # 主动抛异常提示用户补全信息 raise ValidationError("客户姓名不能为空,请补全后再提交") vals = { 'name': record.full_name, 'street': record.address_lineone, 'street2': record.address_linetwo, 'country_id': record.country_id.id if record.country_id else False, 'city': record.city_id.name if record.city_id else False, # 修正为取城市名称而非主键 'state_id': record.state_id.id if record.state_id else False, 'zip': record.post_code, 'phone': record.phone, 'email': record.email, 'customer_rank': 1, 'supplier_rank': 0, 'company_type': 'company', } record.state = 'active' record.env['res.partner'].create(vals) return True # 原有字段定义保持不变 full_name= fields.Char(string='full_name') address_lineone = fields.Char(required=True,string='Address') address_linetwo = fields.Char(string='Line 2') city_id = fields.Many2one('country.city', required=True,string='City', help='Enter City') post_code = fields.Char(required=True,string='Post Code') state_id = fields.Many2one("res.country.state", string='State', help='Enter State', ondelete='restrict') country_id = fields.Many2one('res.country', string='Country', help='Select Country', ondelete='restrict') phone_code = fields.Integer(string='Tel', related='country_id.phone_code', store=True) phone = fields.Char(string='Phone') email = fields.Char(required=True,string='Email')
内容的提问来源于stack exchange,提问作者mazzaya sudan
相关产品推荐
相关产品推荐

