How to Implement _check_company_auto in Odoo?


What is _check_company_auto = True?

_check_company_auto = True is a model-level attribute in Odoo that enables automatic multi-company consistency checks on all Many2one fields that are company-dependent.

When this attribute is set, Odoo automatically verifies that linked records belong to the same company as the main record.


✅ Purpose

To enforce multi-company data integrity by preventing inconsistent relationships between records belonging to different companies.


✅ Where to Define

This is declared in the Python class of a model:


class StockPicking(models.Model):

    _inherit = 'stock.picking'

    _check_company_auto = True



🔍 What Happens When Enabled?

Whenever a record is created or updated, Odoo will automatically check that all relevant Many2one fields (like partner_id, warehouse_id, journal_id, etc.) point to records of the same company as the main record’s company_id.

If there's a mismatch, Odoo raises a ValidationError.



📌 Realistic Example


Scenario:

You have a custom model that links to account.journal and res.partner, and both of those are company-dependent.​


With _check_company_auto = True:


class MyModel(models.Model):

    _name = 'my.model'

    _check_company_auto = True


    partner_id = fields.Many2one('res.partner', required=True)

    journal_id = fields.Many2one('account.journal', required=True)

    company_id = fields.Many2one('res.company', required=True, default=lambda self: self.env.company)


Now, if you try to assign a journal_id or partner_id that belongs to a different company than company_id, Odoo will raise an error like:

The selected Journal (journal_id) does not belong to the same company as this record.

This helps maintain data isolation and correctness across companies in a multi-company environment.



✅ Summary Table


Attribute

Purpose

Applied On

Behavior

_check_company_auto

Enforces company consistency

Many2one fields to company-dependent models

Raises error on mismatch

Default

False (you must explicitly enable it)

Custom models or inherited models

Used in multi-company configurations