NeuroAgent

Odoo 13 Database Recovery: KeyError company_id Fix

Complete guide to fixing KeyError: 'company_id' in Odoo 13. Learn recovery steps for corrupted databases, module reinstallation, and preventive measures to protect your production environment.

Question

Odoo 13 Database Corruption: Core Modules Uninstalled and Recovery Error

I have a running production instance with existing data in my production database. Recently, I encountered an error, and upon investigation, I discovered that some core modules were unexpectedly uninstalled for unknown reasons.

When I attempted to uninstall and reinstall the affected modules, the following error appeared:

2025-11-04 07:37:54,956 6424 ERROR prod_db odoo.modules.registry: Failed to load registry 
Traceback (most recent call last):
  File "/opt/odoo13/odoo/odoo/modules/registry.py", line 87, in new
    odoo.modules.load_modules(registry._db, force_demo, status, update_module)
  File "/opt/odoo13/odoo/odoo/modules/loading.py", line 437, in load_modules
    registry.setup_models(cr)
  File "/opt/odoo13/odoo/odoo/modules/registry.py", line 263, in setup_models
    model._setup_fields()
  File "/opt/odoo13/odoo/odoo/models.py", line 2749, in _setup_fields
    field.setup_full(self)
  File "/opt/odoo13/odoo/odoo/fields.py", line 433, in setup_full
    self._setup_related_full(model)
  File "/opt/odoo13/odoo/odoo/fields.py", line 486, in _setup_related_full
    field = target._fields[name]
KeyError: 'company_id'

Questions:

  1. What might have caused the core modules to uninstall themselves unexpectedly in Odoo 13?
  2. How can I properly recover from this “KeyError: ‘company_id’” error when trying to reinstall modules?
  3. What steps should I take to restore the database to a working state?

Any insights or recommendations would be greatly appreciated.

NeuroAgent

The KeyError: ‘company_id’ error in your Odoo 13 database typically occurs when core module data becomes corrupted or when field references are missing from the database schema. This often happens when modules are improperly uninstalled or when database integrity is compromised, leaving behind orphaned references to fields that no longer exist in their original modules. To recover, you’ll need to perform manual database interventions to clean up these references and restore the missing field definitions.

Contents

Understanding the Root Causes

Unexpected Module Uninstallation

Based on the research findings, there are several potential causes for core modules uninstalling themselves unexpectedly in Odoo 13:

Database Corruption Scenarios

  • The error trace indicates that the issue occurs during module loading when Odoo tries to set up fields and encounters a missing company_id field
  • This suggests that either the field definition was removed from the model or the module containing this field was uninstalled without proper cleanup
  • According to Odoo forum discussions, similar KeyErrors often occur when modules are uninstalled but their data references remain in the database

Dependency Chain Issues

  • Core modules like base, web, or account often have interdependent relationships
  • When one module in this chain is affected, it can cause cascading failures
  • The GitHub issue #1118 shows how Multi-Company module issues can trigger KeyError problems throughout the system

Manual Intervention Gone Wrong

  • Some users report accidentally deleting models or fields through database operations
  • The Stack Overflow discussion mentions that even newcomers can encounter this issue when making database changes

Why company_id Specifically?

The company_id field is particularly prone to these issues because:

Multi-Company Architecture

  • In Odoo 13, the company_id field is crucial for multi-company functionality
  • It’s referenced across many modules including accounting, HR, and CRM
  • When this field becomes unavailable, it breaks the entire multi-company system

Field Reference Problems

  • As explained in the Stack Overflow answer, the error occurs when “a related field inside the module having company_id is given in it”
  • This suggests that some custom module or view is trying to access the company_id field but can’t find it

Immediate Recovery Steps

Database-Level Interventions

1. Connect to PostgreSQL and Check Model Integrity

bash
sudo su - postgres
psql your_database_name

2. Verify ir_model Records
Check if the model containing company_id still exists in the database:

sql
SELECT * FROM ir_model WHERE model = 'res.users';
SELECT * FROM ir_model WHERE model = 'account.move';

3. Manual Cleanup of Orphaned References
If models are missing but references remain, you’ll need to clean them up. According to the Odoo forum solution:

“Simply find these identifiers and delete them and KeyError disappears.”

4. Check for Missing Field Definitions

sql
-- Check if company_id field exists in the model
SELECT * FROM ir_model_fields WHERE name = 'company_id' AND model = 'res.users';

Module Reinstallation Strategy

1. Identify Affected Modules
Based on the error trace and your knowledge of what was uninstalled, identify which core modules are affected.

2. Safe Reinstallation Process

  • First, try to reinstall just the base module using Odoo’s web interface or command line
  • If that fails, proceed with manual database fixes

3. Use Odoo Shell for Emergency Fixes
As shown in the Stack Overflow solution:

bash
sudo python3 /opt/odoo/odoo-bin shell -d your_database_name

Inside the shell, you can manually check and fix field references.


Database Restoration Methods

Option 1: Manual Database Repair

Step 1: Backup Current Database

bash
pg_dump your_database_name > backup_$(date +%Y%m%d_%H%M%S).sql

Step 2: Clean Up Problematic References

sql
-- Remove orphaned model references
DELETE FROM ir_model_data WHERE model NOT IN (SELECT model FROM ir_model);

-- Fix missing field references
DELETE FROM ir_model_fields WHERE name = 'company_id' AND model NOT IN (
    SELECT model FROM ir_model WHERE model IN ('res.users', 'account.move', etc.)
);

Step 3: Restore Missing Module Data
If you know which module provided the company_id field, you may need to restore its data:

sql
-- Example for base module (adjust as needed)
INSERT INTO ir_model_data (name, model, module, res_id, noupdate)
VALUES ('base_company_id', 'res.users', 'base', 1, true)
ON CONFLICT (module, name) DO NOTHING;

Option 2: Fresh Database with Migration

Step 1: Create New Database

bash
createdb new_database_name

Step 2: Install Base Modules Only
Start with a clean database and install only essential modules:

bash
odoo-bin -d new_database_name --without-demo=all --stop-after-init

Step 3: Data Migration Strategy
As suggested in the Odoo forum discussion:

“put all earlier used modules in the modulelist of the dummy database but also to install them in the dummy database, before they where able to do their work for the restored database.”

Step 4: Export/Import Data
Use Odoo’s built-in export/import functionality or PostgreSQL tools to migrate your data carefully.

Option 3: Module-Specific Fixes

Company ID Field Recovery
If the company_id field definition is missing, you may need to recreate it:

python
# In a custom module's models.py
from odoo import fields, models

class ResUsers(models.Model):
    _inherit = 'res.users'
    
    company_id = fields.Many2one('res.company', string='Company')

XML Configuration Fix
Ensure your module’s __manifest__.py includes the necessary security files:

python
'data': [
    'security/ir.model.access.csv',
    'security/security.xml',
],

Preventive Measures

Regular Database Backups

  • Implement automated daily backups
  • Test backup restoration procedures regularly
  • Keep multiple backup versions with different retention periods

Safe Module Management

  • Always test module changes in a development environment first
  • Use proper upgrade procedures rather than manual database operations
  • Document all customizations and their dependencies

Monitoring and Alerting

  • Set up monitoring for database integrity
  • Monitor module installation/uninstallation activities
  • Implement alerts for unusual system behavior

Development Best Practices

  • As noted in the Stack Overflow discussion, ensure all model files are properly included in __init__.py
  • Test field dependencies before deployment
  • Use proper version control for all custom modules

Alternative Recovery Approaches

Using Odoo’s Built-in Repair Tools

Odoo 13 includes some built-in repair mechanisms that can help with database corruption:

Database Check

bash
odoo-bin -d your_database_name --check-stop-after-init

Module Update with Force

bash
odoo-bin -d your_database_name --update=all --stop-after-init

Community Support Resources

  • Odoo Forum: Many users have reported similar issues and found solutions
  • GitHub Issues: Search for similar problems in the Odoo repository
  • Stack Overflow: Look for solutions to specific error patterns

Professional Support Options

For production environments, consider:

  • Odoo Enterprise Support: Official support from Odoo S.A.
  • Odoo Community Association: Community-based support services
  • Third-party Odoo Consultants: Specialized recovery services

Conclusion

Recovering from a KeyError: ‘company_id’ error in Odoo 13 requires systematic troubleshooting and often involves manual database interventions. The key takeaways are:

  1. Start with Database Analysis: Always backup first, then investigate which models and fields are missing or corrupted
  2. Use Incremental Recovery: Begin with manual fixes, then try module reinstallation, and consider fresh database creation as a last resort
  3. Prevent Future Issues: Implement robust backup strategies and safe module management practices

For production environments, it’s often safer to create a fresh database and migrate data carefully rather than trying to repair extensive corruption. The community resources available through Odoo’s forum and GitHub can provide additional insights specific to your particular error pattern.

Sources

  1. Odoo Forum - KeyError uninstalling custom module in Odoo v8
  2. Stack Overflow - Resolving a KeyError in Odoo 13
  3. GitHub Issue - Multi-Company KeyError
  4. Odoo Forum - Facing KeyError: ‘company_id’ (odoo10)
  5. Odoo Forum - How to solve error after restored database
  6. Stack Overflow - KeyError every times upgrade Odoo module
  7. GitHub Issue - Admin ID2 recovery
  8. Stack Overflow - Fields does not exist on Odoo 12