Skip to main content

Globalteckz

Common Odoo ORM Methods

  • Home
  • Common Odoo ORM Methods
odoo orm methods

Common Odoo ORM Methods

Understanding Common Odoo ORM Methods

Object-Relational Mapping (ORM) is a programming technique that connects object-oriented code with relational database structures. It allows developers to work with records as objects instead of writing SQL queries for every database operation.

In Odoo, the ORM provides a structured way to create, retrieve, update, and manage business data through Python models. Understanding common Odoo ORM methods helps developers build custom modules, automate business processes, and maintain data consistency.

What Is ORM in Odoo?

Odoo uses Python for its business logic and PostgreSQL as its relational database. The ORM acts as the layer between Python models and database tables, allowing developers to work with model records through methods and fields.

For example, a customer in Odoo is represented by a record of the res.partner model. Developers can search for customers, create new contacts, update details, and check records using ORM methods rather than manually managing database queries.

Important: Odoo's ORM handles many database operations, including record creation, updates, access rights, and transaction integration. Developers should generally use the ORM instead of direct SQL unless there is a specific, justified technical requirement.

Common Odoo ORM Methods

The following methods are frequently used when developing Odoo modules. The examples use standard model and environment patterns. Exact behavior can depend on the Odoo version, model, access rights, and context.

search()

1. Search Records

The search() method retrieves records that match a search domain. You can apply a limit, offset, or sort order to control the result set.

partners = self.env['res.partner'].search( [('is_company', '=', True)], limit=10, order='name asc' )

Returns: A recordset containing the matching company contacts.

search_count()

2. Count Matching Records

Use search_count() when you need the number of records matching a domain rather than the records themselves.

count = self.env['res.partner'].search_count( [('is_company', '=', True)] )

Returns: An integer representing the number of matching records.

create()

3. Create New Records

The create() method creates a record using the supplied field values. It returns the newly created record or recordset.

partner = self.env['res.partner'].create({ 'name': 'New Customer', 'company_type': 'company' })

Returns: The newly created partner record.

write()

4. Update Existing Records

The write() method updates fields on every record in the current recordset.

partners = self.env['res.partner'].search( [('is_company', '=', True)], limit=5 ) partners.write({'comment': 'Reviewed'})

Returns: A Boolean indicating whether the operation succeeded.

browse()

5. Access Records by ID

The browse() method creates a recordset from database IDs. It is useful when IDs come from another system or an earlier operation. It does not, by itself, guarantee that every referenced record exists.

partners = self.env['res.partner'].browse( [7, 18, 12] )

Returns: A recordset referring to the supplied IDs.

exists()

6. Check Whether Records Exist

The exists() method returns a recordset containing only records that exist in the database.

record = self.env['res.partner'].browse(partner_id) if not record.exists(): raise ValueError("The partner record does not exist.")

Use case: Validate IDs received from external systems or previous operations.

env.ref()

7. Retrieve a Record by External ID

The environment method env.ref() retrieves a record using its XML ID, also known as an external ID. This is commonly used to reference predefined records supplied by Odoo or installed modules.

public_group = self.env.ref( 'base.group_public' )

Returns: The record associated with that external ID. By default, a missing reference raises an error; use raise_if_not_found=False when appropriate.

ensure_one()

8. Require a Single Record

The ensure_one() method checks that a recordset contains exactly one record. It raises an error if the recordset contains zero or multiple records.

def action_confirm(self): self.ensure_one() # Continue with single-record logic

Use case: Methods that must operate on one record, such as a single sales order or customer.

Quick Comparison of Odoo ORM Methods

MethodPurposeTypical result
search()Find records matching a domainRecordset
search_count()Count records matching a domainInteger
create()Create a new recordCreated record
write()Update fields on recordsBoolean
browse()Build a recordset from IDsRecordset
exists()Keep only records that existRecordset
env.ref()Retrieve a record by XML IDReferenced record
ensure_one()Validate a single-record recordsetReturns no value if valid; otherwise raises an error

Additional ORM Operations Developers Should Know

Recordset Filtering

Use filtered() to filter an existing recordset using a condition, without starting a separate search query.

active_partners = partners.filtered( lambda partner: partner.active )

Mapped Field Values

Use mapped() to collect field values or traverse relational fields across a recordset.

partner_names = partners.mapped('name')

Sorting Records

Use sorted() to return records ordered by a field or a sorting function.

sorted_partners = partners.sorted( key=lambda partner: partner.name or '' )

Deleting Records

The unlink() method deletes records from the database, subject to access rights, model rules, and business constraints.

partner.unlink()

Use deletion carefully, particularly for business records with dependencies or audit requirements.

Benefits and Advantages of ORM Tools

Odoo's ORM helps developers build applications around business objects while reducing the need to manage database operations manually. Key advantages include:

1. Business-Oriented Data Models

Models can represent real business concepts such as customers, products, purchase orders, and invoices, rather than forcing application logic to revolve around raw database tables.

2. Less Repetitive Code

Built-in methods handle common create, read, update, and delete operations, allowing developers to focus on business requirements.

3. Centralized Model Definitions

Fields and relationships are defined in Python models. Odoo's framework manages the corresponding database structure through its model and module mechanisms.

4. Powerful Querying

Search domains provide a consistent way to retrieve records based on field values and logical conditions without manually constructing SQL for every query.

5. Relationship Navigation

Relational fields such as Many2one, One2many, and Many2many allow developers to access related business records through model fields.

6. Flexible Data Access

Domains, context, field selection, and recordset operations help developers retrieve and process data for different business scenarios.

7. Transaction Support

ORM operations participate in Odoo's database transaction handling, helping keep related operations consistent when errors occur.

8. Caching and Prefetching

Odoo's ORM uses a record cache and prefetching mechanisms to reduce unnecessary database queries in common access patterns.

9. Access Rights and Record Rules

ORM operations work within Odoo's security framework. Developers should still ensure that custom code handles permissions appropriately.

10. Managed Record Identifiers

Odoo manages record IDs and database persistence, so developers can generally work with model records instead of manually generating database keys.

Key ORM Concepts: Models, Fields, and Relationships

  • Model: Defines a business object, its fields, and its behavior in Odoo.
  • Fields: Represent data such as names, dates, prices, quantities, and statuses.
  • Relationships: Connect records through relational field types, including Many2one, One2many, and Many2many.
  • Recordsets: Represent collections of records from a model and provide methods for accessing and manipulating them.
  • Environment: Provides access to the current database cursor, user, context, and model registry through self.env.
  • Domain: Defines conditions used by methods such as search() and search_count().

ORM Frameworks in Other Programming Languages

ORM is a general software development concept, not something exclusive to Odoo. Other popular ORM tools and data-access frameworks include:

  • Hibernate: An ORM framework commonly used in Java applications.
  • Entity Framework Core: An object-relational mapper for .NET applications.
  • Django ORM: A database interaction layer included with the Django Python web framework.
  • Active Record: The ORM pattern used by Ruby on Rails.
  • SQLAlchemy: A Python SQL toolkit and ORM.

Best Practices When Using Odoo ORM

  • Use batch operations when processing multiple records instead of making unnecessary calls inside loops.
  • Use precise search domains and suitable limits when you do not need every matching record.
  • Use ensure_one() when a method requires exactly one record, and write other methods to handle recordsets correctly.
  • Check whether externally supplied IDs still exist before using their records.
  • Respect Odoo access rights and record rules. Use elevated access only when the business requirement justifies it.
  • Avoid direct SQL for routine CRUD operations because it can bypass ORM behavior and parts of Odoo's security and consistency mechanisms.
  • Test custom ORM logic against the specific Odoo version you deploy.

Frequently Asked Questions About Odoo ORM

What is ORM in Odoo?

ORM stands for Object-Relational Mapping. In Odoo, it connects Python models and recordsets with PostgreSQL data, providing methods to create, search, update, and delete business records.

What are the most commonly used Odoo ORM methods?

Common methods include search(), search_count(), create(), write(), browse(), exists(), and unlink(). Developers also frequently use recordset methods such as filtered(), mapped(), and sorted().

What is the difference between search() and browse()?

search() finds records using a domain and returns matching records. browse() builds a recordset from specified IDs and does not independently verify that every record exists.

What is the difference between create() and write()?

create() creates new database records from supplied values. write() updates fields on records already represented by the recordset.

What does ensure_one() do in Odoo?

ensure_one() validates that a recordset contains exactly one record. It raises an error when the recordset contains zero or more than one record.

Does Odoo ORM support database transactions?

Yes. ORM operations participate in Odoo's transaction management. Developers should follow Odoo's transaction conventions rather than committing transactions manually in ordinary model methods.

Can developers use SQL instead of Odoo ORM?

Direct SQL is possible for certain specialized requirements, but it must be used carefully. SQL can bypass ORM-level behavior, access checks, and automated field logic, so ORM methods are generally preferable for normal business operations.

Need Help with Odoo Development or Customization?

Odoo ORM knowledge is essential when developing custom modules, automating workflows, integrating external systems, and adapting Odoo to business requirements. A well-designed implementation can help keep business logic organized and data operations maintainable.

Contact Globalteckz to discuss your Odoo development and ERP customization requirements.

Email: sales@globalteckz.com

Understanding Common Odoo ORM methods but before that first let’s understand  What is ORM –  Object-Relational Mapping also called as O/RM or O/R mapping tool. Its a programming technique used to convert data between incompatible type system by using Oriented Programming languages. With the same one can create in effect, a virtual object database that can be used from within the programming language.

Today there are free as well as enterprise packages available for performing ORM and some developers use their own ORM tools by opting to construct them.

ORM Methods in Odoo –

Odoo modeling is based on “objects” but its data is stored in a classical relational database named Postgresql. It is use to fill the gap between Open-objects and SQL tables. Python is the programming language giving the behavior and data description of Open-objects (This is not stored in the database). “ORM” is a python class ancestor of all Open-objects. An Open-object is modeling by a static.

Common Odoo ORM Methods:

  1. search()

Takes a search domain, returns a recordset of matching records. Can return a subset of matching records (offset and limit parameters) and be ordered (order parameter):

self.search([(‘is_company’, ‘=’, True)], limit=1)

Return : res.partner(7, 18, 12, 14, 17, 19, 8, 31, 26, 16, 13, 20, 30, 22, 29, 15, 23, 28, 74)

  1. search_count()

To just check if any record matches a domain, or count the number of records which do, use

Return : Count of record which match domain

  1. create()

            Takes a number of field values, and returns a recordset containing the record created

self.create({‘name’: “New Name”})

Return : res.partner(78)

  1. write()

Takes a number of field values, writes them to all the records in its recordset. Does not return anything.

self.write({‘name’: “Newer Name”})

  1. browse()

Takes a database id or a list of ids and returns a recordset, useful when record ids are obtained from outside Odoo (e.g. round-trip through external system)

self.browse([7, 18, 12])

Return : res.partner(7, 18, 12)

  1. exists()

Returns a new recordset containing only the records which exist in the database. Can be used to check whether a record (e.g. obtained externally) still exists.

            if not record.exists():

                        raise Exception(“The record has been deleted”)

  1. ref()

                        Environment method returning the record matching a provided external ID.

                        env.ref(‘base.group_public’)

                        Return : res.groups(2)

  1. ensure_one()

checks that the recordset is a singleton (only contains a single record), raises an error otherwise:

records.ensure_one()

# is equivalent to but clearer than:

assert len(records) == 1, “Expected singleton”

Benefits & Advantages of ORM Tools

1. ORM tools facilitates implementing the Domain Model pattern .

This one reason supercedes all others, using this pattern means that your model entities based on real business concepts rather than based on your database structure. ORM provide this functionality through mapping between the logical business model and also the physical storage model.

2. Reduction in Code

ORM tools provide a host of services thereby allowing developers to focus on the business logic of the application rather than repetitive CRUD (Create Read Update Delete) logic.

3. Changes to the object model are made in one place.

Once you update your object definitions, the ORM will automatically use the updated structure for retrievals and updates. There are no SQL Update, Delete and Insert statements strewn throughout different layers of the application that need modification.

4. Rich query capability.

ORM tools provide an object oriented query language. This allows application developers to focus on the object model and not to have to be concerned with the database structure or SQL semantics. The ORM tool itself will translate the query language into the appropriate syntax for the database.

5. Navigation.

You can navigate object relationships transparently. Related objects are automatically loaded as needed. For example if you load a PO and you want to access it’s Customer, you can simply access PO.Customer and the ORM will take care of loading the data for you without any effort on your part.

6. Data loads

Data Loads are completely configurable allowing you to load the data appropriate for each scenario. For example in one scenario you might want to load a list of POs without any of it’s child / related objects, while in other scenarios you can specify to load a PO, with all it’s child Line Items, etc.

7. Concurrency support.

Support for multiple users updating the same data simultaneously.

8. Cache management.

Entities are cached in memory thereby reducing load on the database.

9. Transaction management and Isolation

All object changes occur scoped to a transaction. The entire transaction can either be committed or rolled back. Multiple transactions can be active in memory in the same time, and each transactions changes are isolated form on another.

10. Key Management.

Identifiers and surrogate keys are automatically populated and managed.

ORM frameworks provide a way to interact with a relational database using objects in an object-oriented programming language. It allows developers to work with objects in their code and then automatically translates the data between the objects and the database tables. This mapping is typically defined using metadata or configuration, and it helps abstract away the complexities of SQL queries and database schema details. Key concepts in ORM include:
  1. Entity: An entity represents a table in the database. In OOP, an entity is often mapped to a class.
  2. Attributes/Properties: These are the fields or columns in a table, which are represented as properties of an object in OOP.
  3. Relationships: ORM allows you to define relationships between entities, such as one-to-one, one-to-many, or many-to-many relationships.
  4. Mapping: The process of defining how the objects in the code correspond to the tables and columns in the database.
Popular ORM frameworks for various programming languages include:
  • Hibernate: for Java
  • Entity Framework: for .NET
  • Django ORM: for Python
  • Active Record: used in Ruby on Rails
  • Spring Data JPA: for Java with the Spring framework

Conclusion:

With ORM we don’t need to take care about database creation and mapping of the fields between Frontend database. It auto create table and its fields based on classes which we are creating in Odoo. Further, Some times we need to do some calculations and perform some operation before it will add to database which we can overwrite via odoo orm method and manage such operations.

Our Articles related to Odoo 

Leave Comment