How to Implement self.env.cr & commit in Odoo?


What is self.env.cr?

  • self.env.cr refers to the cursor (CR = Cursor) of the current PostgreSQL database connection in Odoo.
  • It allows direct interaction with the database using SQL commands.
  • It is part of the low-level ORM API and typically used for:

    • Raw SQL queries
    • Performance tuning
    • Special data operations


What is .commit()?

  • self.env.cr.commit() commits the current transaction to the database.
  • Once committed, changes are permanently saved and cannot be rolled back.
  • Normally, Odoo handles commits automatically at the end of each HTTP request or cron job.


⚠️ Important Warning

  • Use commit() very cautiously.
  • Committing manually bypasses Odoo's rollback safety mechanism, which can lead to data corruption in case of exceptions.


✅ Realistic Odoo Use Case


1. Raw SQL Query Execution (Using self.env.cr)


self.env.cr.execute("""

    SELECT id, name FROM res_partner

    WHERE is_company = True

""")

results = self.env.cr.fetchall()


for row in results:

    _logger.info(f"ID: {row[0]}, Name: {row[1]}")

2. Manual Commit After Critical Update


self.env.cr.execute("""

    UPDATE res_users SET active = False WHERE login = 'demo_user'

""")

self.env.cr.commit()  # Ensure this update is finalized


✅ Use when operating outside normal ORM flow (e.g., in external scripts or low-level integrations).


🔁 When You Might Need commit()


Scenario

Justification for .commit()

After raw SQL DML operations

To persist changes outside ORM

Inside long-running background tasks

To avoid locking issues or partial saves

External scripts using odoo.api.Environment.manage()

Ensures data integrity after processing


✅ Summary Table


Feature

self.env.cr

.commit()

Type

Cursor (DB connection interface)

Method to save current transaction

Usage

Raw SQL execution

Manually finalize DB changes

Auto-managed

Yes (normally by Odoo)

No – must call explicitly

Caution

Medium (read ops safe)

High (can cause data inconsistency if misused)

Use with ORM

Not required (ORM handles transactions)

Use only when bypassing ORM


🧩 Best Practices

  • Avoid using .commit() unless absolutely necessary.
  • Prefer Odoo ORM methods (create, write, unlink) which handle transactions safely.
  • Log and test all operations when using raw SQL.