a-complete-practical-guide-to-orm-methods-in-odoo-18

A Complete Practical Guide to ORM Methods in Odoo 18

Odoo development heavily relies on ORM (Object Relational Mapping) to interact with the database. Odoo ORM (Object Relational Mapping) is the backbone of backend development. Instead of writing raw SQL, Odoo provides powerful Python methods to interact with the database safely, efficiently, and cleanly.

This guide explains core ORM methods and advanced recordset operations with real examples used in daily Odoo development.

What is ORM in Odoo?

ORM (Object Relational Mapping) is a programming technique that connects Python objects with database tables.

ORM allows developers to:

  • Treat database rows as Python objects

  • Perform CRUD operations without SQL

  • Automatically handle security, access rights, and multi-company rules

Because of these advantages, ORM forms the foundation of backend development in Odoo.

Core ORM Methods in Odoo

create()

The create() method inserts a new record into the database and returns a recordset.

				
					partner = self.env['res.partner'].create({
   'name': 'Satya',
})

				
			

This method is commonly used when creating new customers, products, sales orders, or any custom model records.

write()

The write() method updates existing record(s) in the database.

				
					partner.write({'email': 'test@example.com'})

				
			

This method is frequently used when updating information such as customer emails, order statuses, or product details.

unlink()

The unlink() method permanently deletes record(s) from the database.

				
					partner.unlink()

				
			

Since this action removes data permanently, developers must ensure proper access rights and business rules before using it.

search()

The search() method fetches record(s) from the database based on a domain.

				
					partners = self.env['res.partner'].search([('is_company', '=', True)])

				
			

Domains allow developers to filter records using logical conditions such as equality, inequality, or pattern matching.

browse()

The browse() method creates a recordset for given IDs without querying the database immediately.

				
					partner = self.env['res.partner'].browse(10)
				
			

It is useful when you already know the record ID and want to interact with it directly.

onchange()

The onchange() dynamically updates field values in the UI without saving to the database.

				
					@api.onchange('product_id')
def _onchange_product(self):
   self.price_unit = self.product_id.list_price

				
			

This method improves the user experience by automatically updating fields when related fields change.

@api.constrains

Constraints validate data integrity before committing changes to the database.

				
					@api.constrains('credit_limit')
def _check_limit(self):
   if self.credit_limit < 0:
       raise ValidationError("Invalid credit limit")

				
			

If validation fails, Odoo prevents the record from being saved.

Advanced ORM Recordset Methods

Beyond basic CRUD operations, Odoo provides several advanced recordset methods to manipulate data more efficiently.

filtered()

The filtered() method returns a subset of records that satisfy a Python condition.

				
					companies = partners.filtered(lambda p: p.is_company)
				
			

This is useful when working with recordsets that require additional filtering logic.

mapped()

The mapped() method extracts field values from a recordset into a list.

				
					names = partners.mapped('name')
				
			

It is commonly used for collecting field values quickly.

sorted()

The sorted() method returns records ordered using a Python key.

				
					partners.sorted(lambda p: p.name)
				
			

This helps developers organize records based on specific fields.

exists()

The exists() method removes non-existing (deleted) records from a recordset.

				
					records = records.exists()
				
			

This ensures that the recordset only contains valid records.

sudo()

The sudo() method executes ORM operations with superuser privileges.

				
					self.env['res.partner'].sudo().create({'name': 'Admin'})
				
			

Developers should use this method carefully because it ignores access rights.

with_context()

The with_context() method passes temporary context values to ORM operations.

				
					self.with_context(skip_check=True).write({'state': 'done'})
				
			

Context values help modify behavior during execution.

ensure_one()

The ensure_one() method ensures that the method is called on exactly one record.

				
					self.ensure_one()
				
			

If the recordset contains multiple records, Odoo raises an error.

read()

The read() method fetches field values of an existing recordset.

				
					partner.read(['name', 'email'])
				
			

It returns the values in dictionary format.

search_read()

The search_read() method combines search and read into a single optimized call.

				
					self.env['res.partner'].search_read([], ['name'])
				
			

This method improves performance when both searching and reading records are required.

copy()

The copy() method duplicates an existing record with optional changes.

				
					partner.copy({'name': 'Copy of ' + partner.name})
				
			

This is useful when creating templates or cloning records.

name_get()

The name_get() method controls how records are displayed in many2one fields.

				
					def name_get(self):
   return [(rec.id, rec.name) for rec in self]
				
			

Developers customize this method to display additional information with record names.

name_search()

The name_search() method customizes search behavior in many2one fields.

				
					def name_search(self, name, args=None, operator='ilike', limit=100):
   return self.search([('name', operator, name)], limit=limit).name_get()

				
			

This improves record searching within relational fields.

read_group()

The read_group() method performs grouped queries similar to SQL GROUP BY.

				
					self.env['sale.order'].read_group(
   [], ['amount_total'], ['state']
)

				
			

It is useful for reports, dashboards, and aggregated data.

flush()

The flush() method forces pending ORM operations to be written to the database.

				
					self.flush()
				
			

It ensures that unsaved changes are committed when required.

Why Learning ORM Methods is Essential for Odoo Developers

Understanding ORM methods is essential for building efficient and scalable Odoo modules. These methods allow developers to interact with the database in a structured and secure way without relying on raw SQL queries.

Mastering ORM methods is mandatory for:

  • Writing clean Odoo modules
  • Handling complex business logic
  • Building scalable ERP solutions

This guide gives you both the basics and advanced ORM techniques used in real Odoo 18 projects. For anyone working with Odoo 18 development, strong knowledge of ORM methods is not just useful; it is a fundamental skill that directly impacts the quality and performance of the ERP system.

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut elit tellus, luctus nec ullamcorper mattis, pulvinar dapibus leo.

Picture of Madhu Satya Deva Raju

Madhu Satya Deva Raju

I'm Madhu Satya Deva Raju P, a Junior Odoo Developer passionate about building solutions through Odoo development, customization, and integration. I share insights and experiences here to help others grow in the ERP ecosystem.

Get a free quote