Odoo ORM: A Complete Overview for Developers
In Odoo, ORM stands for Object Relational Mapping.
Odoo ORM is the core layer that allows developers to interact with the PostgreSQL database using Python objects instead of writing SQL queries.
What is ORM in Odoo?
The Odoo ORM maps:
- Python classes (models) → Database tables
- Python objects (records) → Table rows
- Class attributes (fields) → Table columns
This makes database operations simple, secure, and consistent.
Why Odoo Uses ORM?
Odoo ORM helps to:
- Avoid writing raw SQL
- Ensure database security
- Automatically manage relationships
- Handle validations and constraints
- Make code cleaner and maintainable
Example of ORM in Odoo
Model Definition
from odoo import models, fields
class Product(models.Model):
_name = 'custom.product'
_description = 'Custom Product'
name = fields.Char(string="Product Name", required=True)
price = fields.Float(string="Price")
active = fields.Boolean(default=True)
What Happens Automatically?
- Table created: custom_product
- Columns: name, price, active
- CRUD operations are auto-handled
Common ORM Operations
Create Record
self.env['custom.product'].create({
'name': 'Laptop',
'price': 50000,
})
Read/Search Records
products = self.env['custom.product'].search([('price', '>', 30000)])Update Record
products.write({'price': 45000})Delete Record
products.unlink()
Relationships in Odoo ORM
| Field Type | Description |
|---|---|
| Many2one | Many records → One record |
| One2many | One record → Many records |
| Many2many | Many records ↔ Many records |
Example
category_id = fields.Many2one('product.category', string="Category")ORM Environment (env)
The env object gives access to:
- Database cursor
- Current user
- Company
- Context
self.env.user
self.env.company
self.env.context
Advantages of Odoo ORM
- Secure (prevents SQL injection)
- Automatic transactions
- Built-in access control
- Easy relational handling
- Faster development
ORM vs SQL in Odoo
| ORM | SQL |
|---|---|
| Python-based | Query-based |
| Safe & readable | Error-prone |
| Auto permissions | Manual permissions |
| Portable | Database-dependent |
Conclusion
Odoo ORM is the backbone of Odoo development. It abstracts database operations into Python objects, making development faster, safer, and more scalable.