Email sales@vrajatechnologies.com Teams Teams Contact +91 9099928101 Whatsapp +91 73596 28466 Linkedin Linkdin
How to Implement self.env.cr & commit in Odoo?
What is self.env.cr & commit?
  • 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 Use Cases in Odoo

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 operationsTo persist changes outside ORM
Inside long-running background tasksTo 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()
TypeCursor (DB connection interface)Method to save current transaction
UsageRaw SQL executionManually finalize DB changes
Auto-managedYes (normally by Odoo)No – must call explicitly
CautionMedium (read ops safe)High (can cause data inconsistency if misused)
Use with ORMNot 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.