https://www.youtube.com/watch?v=fvX7dHyhSas.
Are you an Odoo developer, a technical consultant, or a power user looking to gain unparalleled control over your Odoo instance? While Odoo’s beautiful interface handles most daily operations, there are times when direct, programmatic interaction with your database is not just convenient but essential. This is where Odoo Shell Access ORM becomes your most potent tool.
This comprehensive guide will walk you through everything you need to know about accessing Odoo’s powerful Object-Relational Mapper (ORM) directly from your terminal. By the end of this tutorial, you’ll be able to perform advanced queries, manipulate data, and debug complex scenarios with efficiency you never thought possible.
This article is inspired by and expands upon the valuable insights shared in the video “Como Ejecutar Odoo en modo SHELL (Acceso ORM Terminal)” available at https://www.youtube.com/watch?v=fvX7dHyhSas.
What is Odoo Shell and Why is it Indispensable?
Odoo Shell is a command-line interface (CLI) that allows you to interact with your Odoo application’s framework and its underlying database directly. Think of it as a Python interpreter pre-loaded with your Odoo environment, giving you immediate access to models, records, and the entire ORM layer without needing to navigate through the web interface.
The Odoo ORM (Object-Relational Mapper) is Odoo’s core mechanism for interacting with the PostgreSQL database. Instead of writing raw SQL queries, the ORM provides a Pythonic way to perform database operations like creating, reading, updating, and deleting (CRUD) records. When you gain Odoo Shell Access ORM, you get to wield this power directly, making it incredibly useful for:
- Debugging: Quickly inspect variables, test ORM methods, and pinpoint issues without restarting the Odoo server.
- Data Manipulation: Perform bulk updates, create specific test data, or correct data anomalies that are difficult or impossible via the UI.
- Rapid Prototyping and Testing: Test new features or custom module logic on the fly, verifying behavior immediately.
- Database Introspection: Explore your database schema, model definitions, and field properties programmatically.
- Automation: Execute scripts or complex operations that might be part of a larger automation workflow.
For anyone who dives deep into Odoo’s technical side, mastering Odoo Shell Access ORM is not just an advantage; it’s a fundamental skill.
Prerequisites for Seamless Odoo Shell Access ORM
Before we jump into the steps, ensure you have the following:
- An Odoo Installation: This guide assumes you have a working Odoo instance (either self-hosted or a development environment). The exact path and execution command might vary slightly based on your installation method (e.g., source code, Docker, custom script).
- Basic Command-Line (Terminal) Familiarity: You should be comfortable navigating directories (
cd) and executing commands in your operating system’s terminal (Linux/macOS) or Command Prompt/PowerShell (Windows). - Administrator Privileges: To execute the Odoo shell command and interact with the database, you’ll typically need appropriate user permissions on your system and within Odoo.
- Conceptual Understanding of Odoo ORM (Recommended): While not strictly required to follow the steps, a basic grasp of Odoo models, records, and ORM methods will significantly enhance your ability to utilize the shell effectively. If you’re new to Odoo ORM, consider reading up on Odoo’s official ORM documentation.
Step-by-Step Guide: Gaining Odoo Shell Access ORM
Let’s dive into the practical steps to unleash the power of your Odoo shell.
Step 1: Navigate to Your Odoo Installation Directory
The first crucial step is to open your terminal and change your current directory to where your Odoo source code or executable is located.
For Linux/macOS:
- Open your terminal application.
- Use the
cdcommand to navigate to your Odoo installation directory. Common paths include:/opt/odoo/odoo-server(for many source installations)~/odoo/odoo-bin(if installed in your home directory)cd /path/to/your/odoo/installation- Example: If your Odoo executable is in
/opt/odoo/odoo16/odoo-bin, you would type:
cd /opt/odoo/odoo16You might need to list the contents of a directory (
ls) to find the exact executable name, which is oftenodoo-binorodoo.py.
For Windows:
- Open Command Prompt or PowerShell.
- Navigate to your Odoo installation directory. For example, if Odoo is installed in
C:\Program Files\Odoo 16.0\server:cd "C:\Program Files\Odoo 16.0\server"Remember to use quotation marks if the path contains spaces.
Once you are in the correct directory, you’re ready for the next step.
Step 2: Execute the Odoo Shell Command
With your terminal pointed to the right location, you can now launch the Odoo shell. The command varies slightly depending on your installation:
- Standard Source Installation (Linux/macOS):
./odoo-bin shell -c /etc/odoo/odoo.confOr, if you use a specific Python interpreter:
python3 ./odoo-bin shell -c /etc/odoo/odoo.conf-
Explanation:
./odoo-bin: Executes the Odoo binary from the current directory. (It might beodoo.pyon older versions or specific setups).shell: This is the crucial parameter that tells Odoo to start in shell mode.-c /etc/odoo/odoo.conf: (Optional but recommended) Specifies the path to your Odoo configuration file. This ensures the shell connects to the correct database and uses the right settings. Replace this path with your actual config file location if different.
-
- Windows Installation (usually
odoo-bin.exe):.\odoo-bin.exe shell -c "C:\Program Files\Odoo 16.0\server\odoo.conf" - Docker-based Odoo: If your Odoo is running in a Docker container, you’ll first need to get a shell inside the container:
docker exec -it <container_name_or_id> bashThen, once inside the container, navigate to the Odoo source code directory (e.g.,
/opt/odoo) and run:./odoo-bin shell -c /etc/odoo/odoo.conf
After executing the command, Odoo will initialize the environment. You’ll know it’s successful when you see a prompt like >>> or similar, indicating you are in a Python shell with the Odoo environment loaded.
Step 3: Understanding the Odoo Shell Environment (self and m)
Upon successful launch, you’ll find that Odoo has already provided you with two powerful variables for interacting with the ORM: self and m.
self: Represents anodoo.api.Environmentobject, typically configured for the user who started the Odoo shell (often the administrator orres.userswith ID 1). This is your primary gateway to Odoo’s ORM and its various services.m: Also provides access to the environment, similar toself. It’s a common shortcut to save typing.
Both self.env and m.env refer to the current environment, which is crucial for interacting with Odoo models.
Confirming Your Database Connection:
A good first step is to confirm which database you’re connected to. You can do this by accessing the database cursor:
>>> self.env.cr.dbname
'odoo16_courses' # Output will vary based on your database name
Or using the shortcut m:
>>> m.env.cr.dbname
'odoo16_courses'
This confirms you’re correctly logged into the specified database.
Mastering ORM Interactions within the Odoo Shell
Now that you have Odoo Shell Access ORM, let’s explore some fundamental ORM operations. This is where the real power lies!
1. Retrieving Data (Search & Browse)
The search() method allows you to find records based on specific criteria, while browse() retrieves records by their IDs.
-
Searching for Records:
>>> users = self.env['res.users'].search([]) # Get all users >>> print(users) res.users(1, 4, 5, 6) # Example output: IDs of found users >>> admin_user = self.env['res.users'].search([('login', '=', 'admin')]) >>> print(admin_user.name) # Access a field of the recordset Administrator >>> partners = m.env['res.partner'].search([('is_company', '=', True), ('customer_rank', '>', 0)]) >>> for partner in partners: ... print(f"Company: {partner.name}, City: {partner.city}") ... Company: Odoo S.A., City: Louvain-la-Neuve Company: Your Partner, City: New YorkThe
search()method returns a recordset (a collection of records) or an empty recordset if no matches are found. -
Browsing Records by ID:
If you know the ID of a record,
browse()is faster thansearch().>>> user_id_1 = self.env['res.users'].browse(1) >>> print(user_id_1.name) Administrator >>> specific_product = m.env['product.product'].browse(123) # Replace 123 with an actual product ID >>> if specific_product.exists(): ... print(f"Product Name: {specific_product.name}, Price: {specific_product.list_price}") ...Always check
record.exists()if the ID might not be valid, asbrowse()on a non-existent ID won’t raise an error immediately, but operations on the resulting recordset will fail. -
Combining Search and Read (
search_read):For directly getting dictionaries of data,
search_read()is efficient.>>> invoices_data = self.env['account.move'].search_read( ... [('state', '=', 'posted')], ... ['name', 'amount_total', 'invoice_date'] ... ) >>> for invoice in invoices_data: ... print(invoice) ...
2. Creating Records (create)
Adding new data to your Odoo database is straightforward with the create() method.
>>> new_partner = self.env['res.partner'].create({
... 'name': 'Shell Test Partner',
... 'email': 'shell.test@example.com',
... 'phone': '+1 555 123 4567',
... 'is_company': True,
... 'customer_rank': 1
... })
>>> print(f"Created Partner ID: {new_partner.id}, Name: {new_partner.name}")
Created Partner ID: 105, Name: Shell Test Partner
>>> new_task = m.env['project.task'].create({
... 'name': 'Develop Odoo Shell Tutorial',
... 'user_id': self.env.user.id, # Assign to current user
... 'description': 'Write a comprehensive guide on Odoo Shell access ORM.'
... })
>>> print(f"New Task created: {new_task.name} (ID: {new_task.id})")
The create() method returns the newly created recordset.
3. Updating Records (write)
Modify existing records using the write() method on a recordset.
>>> partner_to_update = self.env['res.partner'].search([('name', '=', 'Shell Test Partner')])
>>> if partner_to_update:
... partner_to_update.write({'city': 'Odoo City', 'zip': '12345'})
... print(f"Partner {partner_to_update.name} updated to City: {partner_to_update.city}")
...
Partner Shell Test Partner updated to City: Odoo City
>>> user_account = m.env['res.users'].browse(2) # Assume user ID 2 exists
>>> if user_account.exists():
... user_account.write({'active': False}) # Deactivate user
... print(f"User {user_account.name} (ID: {user_account.id}) is now inactive.")
...
4. Deleting Records (unlink)
The unlink() method permanently removes records from the database. Use this with extreme caution! There is no undo button in the shell.
>>> partner_to_delete = self.env['res.partner'].search([('name', '=', 'Shell Test Partner')])
>>> if partner_to_delete:
... print(f"Deleting partner: {partner_to_delete.name} (ID: {partner_to_delete.id})")
... partner_to_delete.unlink()
... print("Partner deleted successfully.")
...
Deleting partner: Shell Test Partner (ID: 105)
Partner deleted successfully.
- WARNING: Always double-check your
searchcriteria before callingunlink(). It’s incredibly easy to accidentally delete critical data. It’s highly recommended to test deletion operations on a non-production database first.
5. Executing Raw SQL Queries (Advanced)
While the ORM is preferred for data manipulation, sometimes you might need to run direct SQL queries for complex reporting or database schema introspection. The cr (cursor) object provides this functionality.
>>> self.env.cr.execute("SELECT name, login FROM res_users WHERE active = TRUE")
>>> active_users = self.env.cr.dictfetchall() # Fetch results as a list of dictionaries
>>> for user in active_users:
... print(f"Name: {user['name']}, Login: {user['login']}")
...
Name: Administrator, Login: admin
Name: Mitchell Admin, Login: mitchell
>>> m.env.cr.execute("SELECT count(*) FROM res_partner")
>>> partner_count = m.env.cr.fetchone()[0] # Fetch a single value
>>> print(f"Total Partners: {partner_count}")
Total Partners: 150
- WARNING: Direct SQL bypasses Odoo’s ORM logic, security rules, and ORM caches. Use it sparingly and only when the ORM cannot achieve your goal. Be extremely careful with
INSERT,UPDATE, orDELETEstatements as they can lead to data inconsistencies if not handled correctly.
Practical Use Cases for Odoo Shell Access ORM
The true value of Odoo Shell Access ORM shines in real-world scenarios:
- Debugging Module Installation Errors: If a custom module fails to install, you can use the shell to inspect database tables, fix corrupted data, or manually activate/deactivate modules.
- Bulk Data Migrations: When migrating data from an external system or between Odoo databases, you can write Python scripts in the shell to transform and import large datasets efficiently.
- Applying Hotfixes: In urgent situations, a quick
write()operation in the shell can fix critical data for a few records without deploying a full code update. - Testing Access Rights: You can simulate operations as different users (
self.env.sudo(user_id)) to verify if security rules are working as expected. - Performance Profiling: Test the execution time of complex ORM queries to identify bottlenecks.
- Developing and Testing ORM Methods: Before integrating new ORM methods into a module, you can test their behavior in isolation within the shell.
Best Practices and Safety Tips when using Odoo Shell
While powerful, Odoo Shell Access ORM comes with significant responsibility. Follow these best practices to avoid pitfalls:
- Always Test on Development/Staging Environments First: Never experiment with the Odoo shell directly on a production database unless you absolutely know what you’re doing and have a recent backup.
- Backup Your Database: Before performing any significant data manipulation, ensure you have a fresh backup of your Odoo database. This is your ultimate safety net.
- Understand the ORM: A strong grasp of Odoo’s ORM concepts, model definitions, and relationships is crucial to prevent unintended consequences.
-
Use Transactions (
commit()androllback()): For critical operations, wrap them in a transaction.>>> try: ... self.env.cr.execute("INSERT INTO my_custom_table (field1) VALUES ('test')") ... self.env['res.partner'].create({'name': 'Another Test Partner'}) ... self.env.cr.commit() # Save changes ... print("Operations committed.") ... except Exception as e: ... self.env.cr.rollback() # Discard changes on error ... print(f"Error: {e}. Operations rolled back.") ...If you don’t explicitly
commit(), changes might not be saved until the shell session ends or if auto-commit is enabled (which is not the default for interactive sessions). - Be Mindful of Permissions: The
selfandmobjects often operate with administrator privileges. Be aware that any operation you perform will bypass normal user access rights. If you need to test as a specific user, useself.env(user=user_record). - Document Your Operations: For complex or critical shell scripts, save them in a file. This provides a record of what was done and allows for reusability.
- Exit Gracefully: Type
exit()or pressCtrl+Dto leave the shell session.
Common Challenges and Troubleshooting
Even with careful steps, you might encounter issues:
odoo-bin: command not found: You are likely not in the correct directory. Double-check yourcdcommand in Step 1.Access denied for user "odoo_user" to database "your_db": Your Odoo configuration file (odoo.conf) might have incorrect database credentials, or the database user doesn’t have permissions.AttributeError: 'odoo.models.Model' object has no attribute 'non_existent_field': You’re trying to access a field that doesn’t exist on the model. Check the field’s name and existence.odoo.exceptions.MissingError: Record does not exist or has been deleted.: You tried tobrowseor operate on a record ID that is no longer valid.- ORM Caching Issues: Sometimes, after a direct database change (e.g., via SQL or another session), the ORM cache in your current shell session might be stale. You can try to clear the cache for a model by reloading it or restarting the shell if necessary.
Conclusion
Gaining Odoo Shell Access ORM is a game-changer for anyone working on the technical side of Odoo. It transforms your ability to interact with the database, debug issues, and automate tasks, moving you from a user of the interface to a master of the underlying framework. While it demands a level of caution and understanding, the benefits in terms of efficiency and control are immense.
By following this step-by-step guide and adhering to best practices, you can confidently leverage this powerful tool to streamline your Odoo development and administration workflows. Embrace the command line, unlock your Odoo instance’s full potential, and elevate your technical prowess.
If you found this guide helpful, consider giving it a like! For more advanced techniques and comprehensive training on Odoo for consultants, technicians, and partners, we invite you to explore campuscleverit.es, where you can further deepen your Odoo knowledge. Don’t forget to subscribe for more essential Odoo tips and tutorials!
Discover more from teguhteja.id
Subscribe to get the latest posts sent to your email.

