Globalteckz a leading software development company in Mumbai with over 14+ years of ERP Experience, offering solutions in Odoo, ERPNext, and business automation for startups and enterprises. With a skilled team, we deliver customized implementation and support to streamline operations and drive digital transformation across the globe, India, UAE, USA, Canada, and the UK.
Call/WhatsApp:
+(91) 9820058080
+(91) 9773530597
Email: sales@globalteckz.com
Teams/Skype
kadriazhar | abraar.patel
Copyright © 2026 | Globalteckz - (Mumbai - India). All rights reserved. | Terms and Conditions
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.partnermodel. Developers can search for customers, create new contacts, update details, and check records using ORM methods rather than manually managing database queries.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.
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.
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.
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.
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.
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.
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.
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=Falsewhen appropriate.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 logicUse case: Methods that must operate on one record, such as a single sales order or customer.
Quick Comparison of Odoo ORM Methods
search()search_count()create()write()browse()exists()env.ref()ensure_one()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, andMany2manyallow 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
Many2one,One2many, andMany2many.self.env.search()andsearch_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:
Best Practices When Using Odoo ORM
ensure_one()when a method requires exactly one record, and write other methods to handle recordsets correctly.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(), andunlink(). Developers also frequently use recordset methods such asfiltered(),mapped(), andsorted().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
Related Odoo Articles
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:
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)
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
Takes a number of field values, and returns a recordset containing the record created
self.create({‘name’: “New Name”})
Return : res.partner(78)
Takes a number of field values, writes them to all the records in its recordset. Does not return anything.
self.write({‘name’: “Newer Name”})
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)
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”)
Environment method returning the record matching a provided external ID.
env.ref(‘base.group_public’)
Return : res.groups(2)
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:- Entity: An entity represents a table in the database. In OOP, an entity is often mapped to a class.
- Attributes/Properties: These are the fields or columns in a table, which are represented as properties of an object in OOP.
- Relationships: ORM allows you to define relationships between entities, such as one-to-one, one-to-many, or many-to-many relationships.
- 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: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