KSA | Bahrain | UAE | India

Odoo ORM and CRUD Operations in Odoo 20: A Practical Developer’s Guide

Odoo ORM and CRUD Operations

Every time you create a customer, update a product price, confirm a sales order, or remove an outdated record in Odoo, the system interacts with its database.

But how does Odoo perform these operations? How can developers retrieve records, update information, and create new business data without writing SQL queries for every database operation?

Understanding Odoo ORM and CRUD Operations is the single most important step in moving from Odoo configuration to custom module development

Odoo ORM provides a Python-based interface for interacting with database records. Developers can work with business models and records using methods such as create(), search(), write(), and unlink() while Odoo manages the underlying database operations.

At the centre of this functionality are CRUD operations: Create, Read, Update, and Delete. These four operations form the foundation of database management and are used throughout almost every Odoo application.

In this guide, we will explore how Odoo ORM works, understand its core concepts, and implement CRUD operations through practical Python examples in Odoo 20.

1. What Is ORM in Odoo 20?

ORM stands for Object-Relational Mapping. It is a programming technique that connects object-oriented programming concepts with relational databases.

Odoo uses PostgreSQL as its database management system. However, developers generally do not need to write SQL queries directly to create or manage business records.

Instead, Odoo provides Python models that represent database entities. Developers interact with these models through the ORM framework.

For example, Odoo provides models such as:

Odoo Model Purpose
res.partner Customers, suppliers, and contacts
res.users System users
product.product Product variants
sale.order Sales orders
purchase.order Purchase orders
account.move Invoices and journal entries
hr.employee Employee records

Consider a customer stored in the res.partner model.

Instead of writing an SQL query to insert a new customer into the database, a developer can use:

customer = env['res.partner'].create({
    'name': 'ABC Technologies',
    'email': 'contact@abc.com',
    'phone': '9876543210',
})

Odoo handles the database interaction through its ORM.

The developer works with Python objects and recordsets, while Odoo manages field handling, business logic, and database operations.

2. Understanding Models, Records, and Recordsets

Before working with CRUD operations, it is important to understand three basic concepts: models, records, and recordsets.

2.1 Models

A model represents a business entity in Odoo.

For example, the res.partner model represents contacts, customers, and suppliers.

Developers can create custom models using Python:

from odoo import models, fields

class TrainingCourse(models.Model):
    _name = 'training.course'
    _description = 'Training Course'

    name = fields.Char(string='Course Name')
    duration = fields.Integer(string='Duration')
    fee = fields.Float(string='Course Fee')

Here:

  • models.Model makes the class an Odoo model.
  • _name defines the technical model name.
  • _description provides its description.
  • fields.Char, fields.Integer, and fields.Float define the model’s fields.

When the module is installed, Odoo creates and manages the corresponding database structure.

2.2 Records

A record represents an individual entry in a model.

For example, if the training.course model contains three courses:

ID Course Name Duration Fee
1 Python Development 30 5000
2 Web Development 45 7000
3 Data Analytics 60 9000

Each row represents an individual record.

A record can be accessed using its database ID:

course = env['training.course'].browse(1)

This creates a recordset representing the course with ID 1.

2.3 Recordsets

A recordset is an ordered collection of records belonging to the same model.

It can contain:

  • No records.
  • A single record.
  • Multiple records.

For example:

courses = env['training.course'].browse([1, 2, 3])

This returns a recordset containing three course records.

You can iterate through the recordset:

for course in courses:
    print(course.name)

Each iteration provides access to an individual record.

Recordsets are central to Odoo ORM. Most model methods operate on recordsets rather than individual database rows.

Important: A recordset can contain multiple records, so developers must understand when a method expects a single record and when it can work with multiple records.

3. Understanding the Odoo Environment (self.env)

One of the most frequently used expressions in Odoo development is:

self.env

The environment provides access to the current Odoo execution context.

It contains information such as:

  • The current database cursor.
  • The current user.
  • The current company.
  • Context values.
  • Access to Odoo models.

Developers use the environment to access different models.

For example:

self.env['res.partner']

This returns an empty recordset representing the res.partner model in the current environment.

You can use it to create, search, update, or delete customer records.

Accessing Different Models

partners = self.env['res.partner']

products = self.env['product.product']

sales_orders = self.env['sale.order']

Each expression provides access to a different model.

Understanding self.env in a Model Method

Consider:

def get_companies(self):
    companies = self.env['res.partner'].search([
        ('is_company', '=', True)
    ])
    return companies

Here:

  1. self.env accesses the current environment.
  2. self.env['res.partner'] accesses the contact model.
  3. search() retrieves matching company records.
  4. The resulting recordset is returned.

Understanding the environment is essential because almost every ORM operation begins by accessing a model through self.env.

4. What Are CRUD Operations?

CRUD represents the four fundamental operations used to manage database records.

Operation Meaning Common Odoo ORM Methods
Create Add new records create()
Read Retrieve existing records search(), browse(), read(), search_read()
Update Modify existing records write()
Delete Remove records unlink()

These operations are used across Odoo applications, from managing customers to processing inventory and accounting transactions.

Let’s understand each operation with practical examples.

5. Create Operation , Adding New Records

The Create operation inserts new records into an Odoo model.

Odoo provides the create() method for this purpose.

Syntax

record = env['model.name'].create({
    'field_name': value,
})

The method accepts a dictionary containing field names and their corresponding values.

Example: Creating a Customer

customer = env['res.partner'].create({
    'name': 'ABC Technologies',
    'email': 'contact@abc.com',
    'phone': '9876543210',
})

This creates a new contact record in the res.partner model.

The returned value is a recordset representing the newly created customer.

You can access its fields:

print(customer.name)
print(customer.email)
print(customer.id)

Creating Multiple Records

Odoo supports creating multiple records through a single create() call.

customers = env['res.partner'].create([
    {
        'name': 'ABC Technologies',
        'email': 'abc@example.com',
    },
    {
        'name': 'XYZ Solutions',
        'email': 'xyz@example.com',
    },
    {
        'name': 'Global Systems',
        'email': 'global@example.com',
    },
])

The method returns a recordset containing the newly created records.

Batch creation is generally preferable to repeatedly calling create() inside a loop when the same operation can be performed together.

Overriding create() in a Custom Model

Developers sometimes need to execute additional business logic whenever a record is created.

For this purpose, Odoo provides the @api.model_create_multi decorator.

Example:

from odoo import api, models

class TrainingCourse(models.Model):
    _name = 'training.course'

    @api.model_create_multi
    def create(self, vals_list):
        for vals in vals_list:
            if 'name' in vals:
                vals['name'] = vals['name'].strip()

        return super().create(vals_list)

This example removes unnecessary spaces from course names before creating the records.

@api.model_create_multi is designed for create overrides that can receive multiple dictionaries in vals_list. It allows custom logic to work correctly with batch creation.

6. Read Operation , Retrieving Existing Records

The Read operation retrieves information from existing database records.

Odoo provides several ORM methods for accessing records, including:

  • search()
  • browse()
  • read()
  • search_read()
  • search_count()

Each method serves a slightly different purpose.

6.1 Using search()

The search() method retrieves records matching a specified search domain.

Example:

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

This searches for contact records marked as companies.

To access the returned records:

for company in companies:
    print(company.name)
    print(company.email)

The method returns a recordset, allowing developers to access fields and use other ORM methods.

6.2 Understanding Search Domains

A domain is a structured expression used to filter records.

The general structure is:

[
    ('field_name', 'operator', value)
]

For example:

companies = env['res.partner'].search([
    ('name', '=', 'ABC Technologies')
])

This retrieves records whose name exactly matches ABC Technologies.

Some commonly used domain operators include:

Operator Meaning
= Equal to
!= Not equal to
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to
like Case-sensitive substring matching
ilike Case-insensitive substring matching
=like Case-sensitive pattern matching without automatic surrounding wildcards
=ilike Case-insensitive pattern matching without automatic surrounding wildcards
in Matches a value in a list
not in Does not match values in a list
child_of Matches records in a hierarchical relationship
any Matches records with related records satisfying a domain

For example:

products = env['product.product'].search([
    ('list_price', '>', 1000)
])

This retrieves products whose sales price is greater than 1000.

Combining Multiple Conditions

Multiple conditions in a domain are combined using AND by default.

companies = env['res.partner'].search([
    ('is_company', '=', True),
    ('email', '!=', False),
])

This retrieves company contacts that have an email address.

Developers can also use logical operators:

  • & – AND
  • | – OR
  • ! – NOT

These operators use prefix notation. A logical operator appears before the conditions to which it applies.

Example:

records = env['res.partner'].search([
    '|',
    ('name', 'ilike', 'ABC'),
    ('name', 'ilike', 'XYZ'),
])

This retrieves records whose names contain either ABC or XYZ.

Another example:

records = env['res.partner'].search([
    '&',
    ('is_company', '=', True),
    ('email', '!=', False),
])

This explicitly combines the two conditions using AND.

6.3 Using browse()

The browse() method creates a recordset using known database IDs.

Example:

customer = env['res.partner'].browse(15)

This returns a recordset representing the customer with ID 15.

Multiple IDs can also be supplied:

customers = env['res.partner'].browse([10, 15, 20])

An important distinction is that browse() constructs a recordset for the supplied IDs. It does not perform a search using domain conditions.

To check whether the records still exist:

customers = customers.exists()

exists() filters out records that no longer exist. It does not check whether the current user has permission to access them. Normal access rights and record rules must still be respected.

6.4 Using read()

The read() method retrieves field values from records in a dictionary-based format.

Example:

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

company_data = companies.read([
    'name',
    'email',
    'phone'
])

The result is a list of dictionaries containing the requested field values.

For Many2one fields, the traditional read format generally represents the related record as an ID and display-name pair.

For example, a country_id value may look like:

(104, 'United States')

This format is useful when working with data that needs to be represented as dictionaries rather than recordsets.

6.5 Using search_read()

When both searching and retrieving field values are required, search_read() can be convenient.

Example:

company_data = env['res.partner'].search_read(
    [('is_company', '=', True)],
    ['name', 'email', 'phone'],
    limit=10
)

This searches for matching companies and returns the requested field values as a list of dictionaries.

It is particularly useful for data retrieval tasks where a recordset is not required.

6.6 Using search_count()

The search_count() method returns the number of records matching a domain.

Example:

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

Odoo 20 also supports the limit parameter:

company_count = env['res.partner'].search_count(
    [('is_company', '=', True)],
    limit=100
)

The limit acts as an upper bound on the returned count. This can be useful when the exact total is unnecessary and only a threshold matters.

6.7 Limiting and Sorting Search Results

The search() method supports parameters such as limit, offset, and order.

Example:

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

This retrieves a maximum of ten matching records, sorted by name in ascending order.

These options are useful when working with large datasets.

7. Working with Recordset Helpers

Odoo provides several recordset methods that make it easier to filter, transform, sort, and validate records.

7.1 filtered()

The filtered() method selects records that satisfy a condition.

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

active_companies = companies.filtered(
    lambda partner: partner.active
)

This filters the existing recordset and returns only active companies.

7.2 mapped()

The mapped() method extracts a field value or applies a function across records.

Example:

company_names = companies.mapped('name')

This returns a list of company names.

It can also retrieve related records:

countries = companies.mapped('country_id')

This returns a recordset of related countries, with duplicate records removed.

7.3 sorted()

The sorted() method returns a recordset ordered by a field or function.

sorted_companies = companies.sorted(
    key=lambda partner: partner.name
)

Records are sorted by company name.

7.4 ensure_one()

The ensure_one() method verifies that a recordset contains exactly one record.

def update_course(self):
    self.ensure_one()

    self.write({
        'fee': 6000,
    })

If self contains zero or multiple records, Odoo raises an error.

This is useful for methods that are designed to work with a single record.

7.5 exists()

The exists() method returns the records that still exist in the database.

courses = courses.exists()

It is useful when working with recordsets that may contain deleted records.

It should not be treated as an access-rights check.

8. Update Operation – Modifying Existing Records

The Update operation modifies information stored in existing records.

Odoo provides the write() method for updating records.

Syntax

record.write({
    'field_name': new_value,
})

Example: Updating Customer Information

customer = env['res.partner'].browse(15)

customer.write({
    'email': 'newemail@example.com',
    'phone': '9999988888',
})

This updates the email address and phone number of the customer with ID 15.

Updating Multiple Records

The write() method can update multiple records in a single operation.

For example, updating a harmless descriptive field:

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

companies.write({
    'comment': 'Reviewed during data cleanup.',
})

This updates the comment on all matching company records.

Always review the domain before performing bulk updates, particularly in production databases.

Updating a Record Using Field Assignment

Odoo also supports direct field assignment on records.

customer = env['res.partner'].browse(15)

customer.email = 'updated@example.com'

This updates the field through the ORM.

In normal model code, assigning a field triggers an ORM write operation. In an onchange method, however, the assignment updates the in-memory form cache and is not immediately persisted to the database.

For updating several fields together, write() is often clearer.

9. Delete Operation – Removing Existing Records

The Delete operation removes existing records from the database.

Odoo provides the unlink() method for deleting records.

Syntax

record.unlink()

Example: Deleting a Training Course

course = env['training.course'].browse(15)

course.unlink()

This attempts to delete the training course with ID 15.

Deleting Multiple Records

The unlink() method can also delete multiple records:

courses = env['training.course'].search([
    ('duration', '<=', 0)
])

courses.unlink()

This attempts to delete all matching courses.

Use deletion carefully. Other records may depend on the records being deleted, and Odoo may prevent deletion through access rights, business constraints, or relational restrictions.

Archiving Instead of Deleting

In many business workflows, archiving a record is preferable to permanently deleting it.

For models that support the active field, Odoo provides the action_archive() method.

Example:

course = env['training.course'].browse(15)

course.action_archive()

Archiving makes the record inactive without permanently removing its database entry.

This is useful when business records need to be retained for historical reference.

10. Working with Relational Fields Using ORM

Odoo models are connected through relational fields. These relationships allow one record to be associated with other records.

The three main relational field types are Many2one, One2many, and Many2many.

10.1 Many2one

A Many2one field connects one record to another record.

For example, multiple sales orders can belong to the same customer.

partner_id = fields.Many2one(
    'res.partner',
    string='Customer'
)

To assign an existing customer:

order = env['sale.order'].create({
    'partner_id': 15,
})

The value supplied to a Many2one field is the database ID of the related record.

10.2 One2many

A One2many field represents multiple related records through an inverse Many2one field.

For example, a sales order contains multiple order lines.

The actual field on Odoo’s standard sale.order model is named order_line, not order_line_ids.

A simplified field definition looks like:

order_line = fields.One2many(
    'sale.order.line',
    'order_id',
    string='Order Lines'
)

The order_id field on sale.order.line establishes the inverse relationship.

10.3 Many2many

A Many2many field connects multiple records to multiple other records.

For example, a training course can have several participants, and a participant can attend multiple courses.

In our custom training model, we can define:

participant_ids = fields.Many2many(
    'res.partner',
    string='Participants'
)

10.4 Understanding fields.Command

Odoo provides fields.Command to manage One2many and Many2many relationships.

Instead of manually manipulating relationship tables, developers can use these commands.

Command Purpose
Command.create() Create a related record
Command.update() Update a related record
Command.delete() Delete a related record
Command.unlink() Remove a relationship
Command.link() Add an existing relationship
Command.clear() Remove all relationships
Command.set() Replace relationships with specified records

Example:

from odoo.fields import Command

course = env['training.course'].create({
    'name': 'Python Development',
    'participant_ids': [
        Command.link(10),
        Command.link(15),
    ],
})

This creates a training course and links the existing contacts with IDs 10 and 15 as participants.

Another example:

course.write({
    'participant_ids': [
        Command.create({
            'name': 'New Participant',
        }),
    ],
})

For a Many2many field, Command.create() creates one related record and links it to the records in the current recordset.

For One2many fields, it creates a related record for each parent record in the recordset.

Creating a Sales Order with Order Lines

Relational commands are especially useful when creating complex business records.

For example, a sales order can be created with its order lines in a single ORM operation:

from odoo.fields import Command

order = env['sale.order'].create({
    'partner_id': 15,
    'order_line': [
        Command.create({
            'product_id': 25,
            'product_uom_qty': 2,
        }),
        Command.create({
            'product_id': 30,
            'product_uom_qty': 1,
        }),
    ],
})

This example assumes that the Sales application is installed and the referenced customer and products exist.

Odoo handles the creation of the sales order and its related order lines through the ORM.

11. Practical Example: Building a Training Management Module

Now let’s combine the concepts discussed above in a practical example.

We will create a simple Training Management module that allows internal users to manage course records through the Odoo interface.

The example includes:

  • A custom model.
  • CRUD access rights.
  • List and form views.
  • A menu and window action.
  • ORM operations that can be tested through Odoo shell.

Step 1: Create the Module Structure

Create a custom module named training_management.

training_management/
│
├── __init__.py
├── __manifest__.py
│
├── models/
│   ├── __init__.py
│   └── training_course.py
│
├── security/
│   └── ir.model.access.csv
│
└── views/
    └── training_course_views.xml

Step 2: Configure the Manifest

Create the __manifest__.py file:

{
    'name': 'Training Management',
    'version': '1.0',
    'summary': 'Training course management using Odoo ORM',
    'depends': ['base'],
    'data': [
        'security/ir.model.access.csv',
        'views/training_course_views.xml',
    ],
    'installable': True,
    'application': True,
    'license': 'LGPL-3',
}

The base dependency provides the standard Odoo framework and contact model.

The security file is loaded before the views so that the access configuration is available when users interact with the model.

Step 3: Import the Model

In the main __init__.py file:

from . import models

Inside models/__init__.py:

from . import training_course

Step 4: Define the Training Course Model

Create models/training_course.py:

from odoo import models, fields


class TrainingCourse(models.Model):

    _name = 'training.course'
    _description = 'Training Course'

    name = fields.Char(
        string='Course Name',
        required=True
    )

    duration = fields.Integer(
        string='Duration (Days)'
    )

    fee = fields.Float(
        string='Course Fee'
    )

    description = fields.Text(
        string='Description'
    )

    participant_ids = fields.Many2many(
        'res.partner',
        string='Participants'
    )

    active = fields.Boolean(
        default=True
    )

This creates a custom model with course details, participants, and an active status.

Step 5: Configure Access Rights

A custom model does not automatically become accessible to ordinary internal users.

Create the file:

security/ir.model.access.csv

Add:

id,name,model_id:id,group_id:id,perm_read,perm_write,perm_create,perm_unlink
access_training_course_user,training.course user,model_training_course,base.group_user,1,1,1,1

This grants internal users read, write, create, and delete permissions on the training course model.

For a real business application, access rights should be restricted to the groups that genuinely need them. Record rules may also be required when users should only access specific records.

Step 6: Create the Views and Menu

Create views/training_course_views.xml:

<odoo>

    <record id="view_training_course_list"
            model="ir.ui.view">

        <field name="name">training.course.list</field>
        <field name="model">training.course</field>

        <field name="arch" type="xml">
            <list>
                <field name="name"/>
                <field name="duration"/>
                <field name="fee"/>
            </list>
        </field>

    </record>


    <record id="view_training_course_form"
            model="ir.ui.view">

        <field name="name">training.course.form</field>
        <field name="model">training.course</field>

        <field name="arch" type="xml">
            <form>
                <sheet>

                    <group>
                        <field name="name"/>
                        <field name="duration"/>
                        <field name="fee"/>
                        <field name="active"/>
                    </group>

                    <group>
                        <field name="participant_ids"
                               widget="many2many_tags"/>
                    </group>

                    <group>
                        <field name="description"/>
                    </group>

                </sheet>
            </form>
        </field>

    </record>


    <record id="action_training_course"
            model="ir.actions.act_window">

        <field name="name">Training Courses</field>
        <field name="res_model">training.course</field>
        <field name="view_mode">list,form</field>

    </record>


    <menuitem id="menu_training_root"
              name="Training Management"/>

    <menuitem id="menu_training_courses"
              name="Courses"
              parent="menu_training_root"
              action="action_training_course"/>

</odoo>

The XML file defines:

  • A list view for displaying courses.
  • A form view for creating and editing courses.
  • A window action for opening the model.
  • A menu entry for accessing the module.

Step 7: Install the Module

After completing the files:

  1. Restart the Odoo server if required.
  2. Activate Developer Mode.
  3. Navigate to Apps.
  4. Update the Apps List.
  5. Search for Training Management.
  6. Install the module.

After installation, internal users with the configured access rights can open the Training Management menu and manage course records.

Step 8: Test CRUD Operations Using Odoo Shell

Odoo shell provides an interactive Python environment for testing ORM operations.

Start the shell using the appropriate configuration and database:

./odoo-bin shell -c /path/to/odoo.conf -d your_database

The exact command may differ depending on the installation method.

Inside the shell, the env variable is already available.

Create a course:

course = env['training.course'].create({
    'name': 'Python Development',
    'duration': 30,
    'fee': 5000,
    'description': 'Introduction to Python programming',
})

Read course records:

courses = env['training.course'].search([])

for course in courses:
    print(course.name, course.duration, course.fee)

Update a course:

course.write({
    'fee': 6000,
    'duration': 35,
})

Delete a course:

course.unlink()

For a safer alternative, archive it:

course.action_archive()

Important: Odoo shell normally runs within a transaction. Changes are not committed automatically simply because a command was executed. To persist successful changes in an interactive shell session, use:

env.cr.commit()

If you are only testing, you can close the shell without committing to avoid keeping the test changes. Do not manually commit inside ordinary business methods or normal Odoo request handling.

12. Advanced ORM Concepts for Odoo Developers

Beyond the four CRUD operations, Odoo provides additional methods and features for working efficiently with business data.

12.1 Copying Records with copy()

The copy() method creates a duplicate of an existing record.

Example:

course = env['training.course'].browse(10)

new_course = course.copy({
    'name': 'Advanced Python Development',
})

This creates a copy using the original record’s copyable field values, with the course name overridden.

Fields marked with copy=False are not copied in the usual way.

12.2 Aggregating Records with _read_group()

Sometimes developers need aggregated information instead of individual records.

For example, a business may need to calculate total sales by customer or count records by category.

Odoo provides _read_group() for backend aggregation.

Example:

results = env['sale.order']._read_group(
    domain=[('state', '=', 'sale')],
    groupby=['partner_id'],
    aggregates=['amount_total:sum'],
)

This groups confirmed sales orders by customer and calculates the sum of their total amounts.

The returned structure contains grouped values and aggregate results.

Version note: Odoo’s ORM changelog records that read_group() was deprecated in Odoo 18.2 in favour of _read_group() for backend usage and formatted_read_group() as a formatted public API. For new backend code in Odoo 20, consult the current _read_group() signature and return format.

12.3 Using Raw SQL Carefully

Odoo ORM should generally be the first choice for database operations.

Direct SQL bypasses important ORM features such as access rights, record rules, field computations, and cache management.

There are situations where raw SQL may be justified, particularly for specialised database operations or performance-sensitive tasks.

However, developers must keep the ORM cache and database state consistent.

Before executing SQL that depends on pending ORM changes, flush the relevant fields:

self.env['training.course'].flush_model([
    'fee'
])

For example, a raw SQL update may look like:

self.env.cr.execute(
    """
    UPDATE training_course
    SET fee = %s
    WHERE fee = %s
    """,
    [6000, 5000]
)

After direct SQL updates, invalidate the affected ORM cache:

self.env['training.course'].invalidate_model([
    'fee'
])

When direct SQL modifies fields that trigger computed-field dependencies, additional notification through modified() may be necessary.

Use parameterized SQL rather than building queries through string concatenation. Never use raw SQL as a shortcut around Odoo’s security controls.

13. Important ORM Changes and Practices in Odoo 20

Odoo’s ORM has evolved across multiple releases. Developers working with Odoo 20 should be aware of several changes introduced in earlier versions that remain relevant.

13.1 Use domain in Search Methods

Older examples may use the parameter name args when defining or calling search-related methods.

The search API uses domain as the parameter name in modern Odoo versions.

Prefer:

records = env['res.partner'].search(
    domain=[('is_company', '=', True)]
)

13.2 Use display_name Instead of name_get()

Older Odoo code commonly used name_get() to retrieve display labels for records.

The name_get() method was replaced by the display_name field in Odoo 17.

For modern code, use:

display_name = record.display_name

For custom display-name behaviour, developers should use the appropriate display-name computation mechanism rather than implementing older name_get() patterns.

13.3 Use the Current Aggregation API

As explained earlier, read_group() was deprecated in Odoo 18.2 for backend use.

Odoo 20 developers should use _read_group() for backend aggregation and consult the ORM documentation for its current signature and return format.

13.4 search_count() Supports a Limit

The search_count() method accepts a limit parameter.

count = env['training.course'].search_count(
    [('active', '=', True)],
    limit=100
)

This returns the number of matching records up to the specified limit.

These changes are important when adapting older Odoo code or maintaining custom modules across major versions.

14. Common ORM Mistakes and How to Avoid Them

14.1 Forgetting ensure_one()

Some methods are designed to operate on exactly one record.

If they receive a recordset containing multiple records, accessing a field that requires a single record can raise an Expected singleton error.

Use:

def update_course(self):
    self.ensure_one()

    self.write({
        'fee': 6000,
    })

This makes the method’s single-record requirement explicit.

14.2 Performing Searches Inside Loops

Inefficient approach:

for partner in partners:
    orders = env['sale.order'].search([
        ('partner_id', '=', partner.id)
    ])

This performs a separate search for every partner.

A better approach is to retrieve the required records together:

orders = env['sale.order'].search([
    ('partner_id', 'in', partners.ids)
])

You can then group or filter the results as needed.

14.3 Reading a Field from a Multi-Record Recordset

Reading a field directly from a recordset containing multiple records can raise an Expected singleton error.

Incorrect:

print(partners.name)

Correct:

for partner in partners:
    print(partner.name)

Or use:

names = partners.mapped('name')

14.4 Using sudo() Without Understanding Its Impact

sudo() changes the access environment and can bypass normal access restrictions.

Incorrect use may expose sensitive records or allow users to modify information they should not access.

Use elevated access only when the business requirement explicitly justifies it, and carefully consider the security implications.

15. Frequently Asked Questions

What is ORM in Odoo?

ORM stands for Object-Relational Mapping. It allows developers to interact with PostgreSQL database records using Python models and methods rather than writing SQL queries for every operation.

What are CRUD operations in Odoo?

CRUD represents Create, Read, Update, and Delete. These operations allow developers to create new records, retrieve existing information, modify records, and remove records using Odoo ORM methods.

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

search() retrieves records matching a specified domain. browse() creates a recordset using known database IDs. It does not perform a domain search.

What is the difference between write() and direct field assignment?

Both update record fields through the ORM. write() is useful for updating multiple fields or records together, while direct assignment is convenient for setting an individual field. In onchange methods, assignments update the in-memory form cache rather than immediately persisting the change.

What is self.env in Odoo?

self.env provides access to the current Odoo environment, including the database cursor, current user, context, company, and model registry.

What is a recordset?

A recordset is an ordered collection of records belonging to the same Odoo model. It can contain zero, one, or multiple records.

What is the purpose of unlink()?

unlink() deletes records from the database through the ORM, subject to access rights, business restrictions, and relational constraints.

Can we create multiple records using one create() method?

Yes. Odoo supports batch creation by passing a list of dictionaries to create(). When overriding create(), developers should use @api.model_create_multi to support batch operations correctly.

What is fields.Command used for?

fields.Command provides methods for managing One2many and Many2many relationships, including creating, linking, updating, unlinking, and replacing related records.

What is the difference between read() and search_read()?

read() retrieves field values from an existing recordset. search_read() combines searching and reading, returning matching records as dictionaries.

Why should developers use ORM instead of direct SQL?

ORM provides access control, business logic, field handling, relationship management, caching, and other framework features. Direct SQL bypasses many of these mechanisms and requires additional care.

Conclusion

Odoo ORM is one of the most important components of Odoo development. It provides a structured way to interact with database records through Python models, recordsets, and methods.

Understanding CRUD operations is the foundation for building custom Odoo modules. Whether you are creating customer records, retrieving sales orders, updating product information, or removing outdated entries, the ORM provides the methods needed to manage these operations.

By learning create(), search(), browse(), read(), search_read(), write(), and unlink(), developers can build efficient and maintainable applications without relying on direct SQL for routine database operations.

Once you understand ORM fundamentals, you can move towards more advanced topics such as computed fields, constraints, relational commands, domains, context handling, aggregation, and access-control management.

For every Odoo developer, mastering ORM is not just about learning a set of methods. It is about understanding how Odoo applications communicate with and manage their underlying business data.

References and Further Reading

  1. Odoo 20 – ORM API
  2. Odoo 20 – ORM Changelog
  3. Odoo 20 – Security: Access Rights
  4. Odoo 20 – Backend Developer Tutorials

Leave a Reply

Your email address will not be published. Required fields are marked *