{"id":10186,"date":"2026-11-25T16:37:00","date_gmt":"2026-11-25T13:37:00","guid":{"rendered":"https:\/\/machinser.com\/?p=10186"},"modified":"2026-11-25T16:39:14","modified_gmt":"2026-11-25T13:39:14","slug":"odoo-orm-and-crud-operations","status":"publish","type":"post","link":"https:\/\/machinser.com\/ar\/odoo-orm-and-crud-operations\/","title":{"rendered":"Odoo ORM and CRUD Operations in Odoo 20: A Practical Developer&#8217;s Guide"},"content":{"rendered":"<p>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.<\/p>\n<p>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?<\/p>\n<p>Understanding Odoo ORM and CRUD Operations is the single most important step in moving from Odoo configuration to custom module development<\/p>\n<p>Odoo ORM provides a Python-based interface for interacting with database records. Developers can work with business models and records using methods such as <code>create()<\/code>, <code>search()<\/code>, <code>write()<\/code>, and <code>unlink()<\/code> while Odoo manages the underlying database operations.<\/p>\n<p>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.<\/p>\n<p>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.<\/p>\n<h2>1. What Is ORM in Odoo 20?<\/h2>\n<p>ORM stands for Object-Relational Mapping. It is a programming technique that connects object-oriented programming concepts with relational databases.<\/p>\n<p>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.<\/p>\n<p>Instead, Odoo provides Python models that represent database entities. Developers interact with these models through the ORM framework.<\/p>\n<p>For example, Odoo provides models such as:<\/p>\n<table>\n<tbody>\n<tr>\n<th>Odoo Model<\/th>\n<th>Purpose<\/th>\n<\/tr>\n<tr>\n<td><code>res.partner<\/code><\/td>\n<td>Customers, suppliers, and contacts<\/td>\n<\/tr>\n<tr>\n<td><code>res.users<\/code><\/td>\n<td>System users<\/td>\n<\/tr>\n<tr>\n<td><code>product.product<\/code><\/td>\n<td>Product variants<\/td>\n<\/tr>\n<tr>\n<td><code>sale.order<\/code><\/td>\n<td>Sales orders<\/td>\n<\/tr>\n<tr>\n<td><code>purchase.order<\/code><\/td>\n<td>Purchase orders<\/td>\n<\/tr>\n<tr>\n<td><code>account.move<\/code><\/td>\n<td>Invoices and journal entries<\/td>\n<\/tr>\n<tr>\n<td><code>hr.employee<\/code><\/td>\n<td>Employee records<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>Consider a customer stored in the <code>res.partner<\/code> model.<\/p>\n<p>Instead of writing an SQL query to insert a new customer into the database, a developer can use:<\/p>\n<pre><code>customer = env['res.partner'].create({\r\n    'name': 'ABC Technologies',\r\n    'email': 'contact@abc.com',\r\n    'phone': '9876543210',\r\n})<\/code><\/pre>\n<p>Odoo handles the database interaction through its ORM.<\/p>\n<p>The developer works with Python objects and recordsets, while Odoo manages field handling, business logic, and database operations.<\/p>\n<h2>2. Understanding Models, Records, and Recordsets<\/h2>\n<p>Before working with CRUD operations, it is important to understand three basic concepts: models, records, and recordsets.<\/p>\n<h3>2.1 Models<\/h3>\n<p>A model represents a business entity in Odoo.<\/p>\n<p>For example, the <code>res.partner<\/code> model represents contacts, customers, and suppliers.<\/p>\n<p>Developers can create custom models using Python:<\/p>\n<pre><code>from odoo import models, fields\r\n\r\nclass TrainingCourse(models.Model):\r\n    _name = 'training.course'\r\n    _description = 'Training Course'\r\n\r\n    name = fields.Char(string='Course Name')\r\n    duration = fields.Integer(string='Duration')\r\n    fee = fields.Float(string='Course Fee')<\/code><\/pre>\n<p>Here:<\/p>\n<ul>\n<li><code>models.Model<\/code> makes the class an Odoo model.<\/li>\n<li><code>_name<\/code> defines the technical model name.<\/li>\n<li><code>_description<\/code> provides its description.<\/li>\n<li><code>fields.Char<\/code>, <code>fields.Integer<\/code>, and <code>fields.Float<\/code> define the model&#8217;s fields.<\/li>\n<\/ul>\n<p>When the module is installed, Odoo creates and manages the corresponding database structure.<\/p>\n<h3>2.2 Records<\/h3>\n<p>A record represents an individual entry in a model.<\/p>\n<p>For example, if the <code>training.course<\/code> model contains three courses:<\/p>\n<table>\n<tbody>\n<tr>\n<th>ID<\/th>\n<th>Course Name<\/th>\n<th>Duration<\/th>\n<th>Fee<\/th>\n<\/tr>\n<tr>\n<td>1<\/td>\n<td>Python Development<\/td>\n<td>30<\/td>\n<td>5000<\/td>\n<\/tr>\n<tr>\n<td>2<\/td>\n<td>Web Development<\/td>\n<td>45<\/td>\n<td>7000<\/td>\n<\/tr>\n<tr>\n<td>3<\/td>\n<td>Data Analytics<\/td>\n<td>60<\/td>\n<td>9000<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>Each row represents an individual record.<\/p>\n<p>A record can be accessed using its database ID:<\/p>\n<pre><code>course = env['training.course'].browse(1)<\/code><\/pre>\n<p>This creates a recordset representing the course with ID 1.<\/p>\n<h3>2.3 Recordsets<\/h3>\n<p>A recordset is an ordered collection of records belonging to the same model.<\/p>\n<p>It can contain:<\/p>\n<ul>\n<li>No records.<\/li>\n<li>A single record.<\/li>\n<li>Multiple records.<\/li>\n<\/ul>\n<p>For example:<\/p>\n<pre><code>courses = env['training.course'].browse([1, 2, 3])<\/code><\/pre>\n<p>This returns a recordset containing three course records.<\/p>\n<p>You can iterate through the recordset:<\/p>\n<pre><code>for course in courses:\r\n    print(course.name)<\/code><\/pre>\n<p>Each iteration provides access to an individual record.<\/p>\n<p>Recordsets are central to Odoo ORM. Most model methods operate on recordsets rather than individual database rows.<\/p>\n<p>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.<\/p>\n<h2>3. Understanding the Odoo Environment (<code>self.env<\/code>)<\/h2>\n<p>One of the most frequently used expressions in Odoo development is:<\/p>\n<pre><code>self.env<\/code><\/pre>\n<p>The environment provides access to the current Odoo execution context.<\/p>\n<p>It contains information such as:<\/p>\n<ul>\n<li>The current database cursor.<\/li>\n<li>The current user.<\/li>\n<li>The current company.<\/li>\n<li>Context values.<\/li>\n<li>Access to Odoo models.<\/li>\n<\/ul>\n<p>Developers use the environment to access different models.<\/p>\n<p>For example:<\/p>\n<pre><code>self.env['res.partner']<\/code><\/pre>\n<p>This returns an empty recordset representing the <code>res.partner<\/code> model in the current environment.<\/p>\n<p>You can use it to create, search, update, or delete customer records.<\/p>\n<h3>Accessing Different Models<\/h3>\n<pre><code>partners = self.env['res.partner']\r\n\r\nproducts = self.env['product.product']\r\n\r\nsales_orders = self.env['sale.order']<\/code><\/pre>\n<p>Each expression provides access to a different model.<\/p>\n<h3>Understanding <code>self.env<\/code> in a Model Method<\/h3>\n<p>Consider:<\/p>\n<pre><code>def get_companies(self):\r\n    companies = self.env['res.partner'].search([\r\n        ('is_company', '=', True)\r\n    ])\r\n    return companies<\/code><\/pre>\n<p>Here:<\/p>\n<ol start=\"1\">\n<li><code>self.env<\/code> accesses the current environment.<\/li>\n<li><code>self.env['res.partner']<\/code> accesses the contact model.<\/li>\n<li><code>search()<\/code> retrieves matching company records.<\/li>\n<li>The resulting recordset is returned.<\/li>\n<\/ol>\n<p>Understanding the environment is essential because almost every ORM operation begins by accessing a model through <code>self.env<\/code>.<\/p>\n<h2>4. What Are CRUD Operations?<\/h2>\n<p>CRUD represents the four fundamental operations used to manage database records.<\/p>\n<table>\n<tbody>\n<tr>\n<th>Operation<\/th>\n<th>Meaning<\/th>\n<th>Common Odoo ORM Methods<\/th>\n<\/tr>\n<tr>\n<td>Create<\/td>\n<td>Add new records<\/td>\n<td><code>create()<\/code><\/td>\n<\/tr>\n<tr>\n<td>Read<\/td>\n<td>Retrieve existing records<\/td>\n<td><code>search()<\/code>, <code>browse()<\/code>, <code>read()<\/code>, <code>search_read()<\/code><\/td>\n<\/tr>\n<tr>\n<td>Update<\/td>\n<td>Modify existing records<\/td>\n<td><code>write()<\/code><\/td>\n<\/tr>\n<tr>\n<td>Delete<\/td>\n<td>Remove records<\/td>\n<td><code>unlink()<\/code><\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>These operations are used across Odoo applications, from managing customers to processing inventory and accounting transactions.<\/p>\n<p>Let&#8217;s understand each operation with practical examples.<\/p>\n<h2>5. Create Operation , Adding New Records<\/h2>\n<p>The Create operation inserts new records into an Odoo model.<\/p>\n<p>Odoo provides the <code>create()<\/code> method for this purpose.<\/p>\n<h3>Syntax<\/h3>\n<pre><code>record = env['model.name'].create({\r\n    'field_name': value,\r\n})<\/code><\/pre>\n<p>The method accepts a dictionary containing field names and their corresponding values.<\/p>\n<h3>Example: Creating a Customer<\/h3>\n<pre><code>customer = env['res.partner'].create({\r\n    'name': 'ABC Technologies',\r\n    'email': 'contact@abc.com',\r\n    'phone': '9876543210',\r\n})<\/code><\/pre>\n<p>This creates a new contact record in the <code>res.partner<\/code> model.<\/p>\n<p>The returned value is a recordset representing the newly created customer.<\/p>\n<p>You can access its fields:<\/p>\n<pre><code>print(customer.name)\r\nprint(customer.email)\r\nprint(customer.id)<\/code><\/pre>\n<h3>Creating Multiple Records<\/h3>\n<p>Odoo supports creating multiple records through a single <code>create()<\/code> call.<\/p>\n<pre><code>customers = env['res.partner'].create([\r\n    {\r\n        'name': 'ABC Technologies',\r\n        'email': 'abc@example.com',\r\n    },\r\n    {\r\n        'name': 'XYZ Solutions',\r\n        'email': 'xyz@example.com',\r\n    },\r\n    {\r\n        'name': 'Global Systems',\r\n        'email': 'global@example.com',\r\n    },\r\n])<\/code><\/pre>\n<p>The method returns a recordset containing the newly created records.<\/p>\n<p>Batch creation is generally preferable to repeatedly calling <code>create()<\/code> inside a loop when the same operation can be performed together.<\/p>\n<h3>Overriding <code>create()<\/code> in a Custom Model<\/h3>\n<p>Developers sometimes need to execute additional business logic whenever a record is created.<\/p>\n<p>For this purpose, Odoo provides the <code>@api.model_create_multi<\/code> decorator.<\/p>\n<p>Example:<\/p>\n<pre><code>from odoo import api, models\r\n\r\nclass TrainingCourse(models.Model):\r\n    _name = 'training.course'\r\n\r\n    @api.model_create_multi\r\n    def create(self, vals_list):\r\n        for vals in vals_list:\r\n            if 'name' in vals:\r\n                vals['name'] = vals['name'].strip()\r\n\r\n        return super().create(vals_list)<\/code><\/pre>\n<p>This example removes unnecessary spaces from course names before creating the records.<\/p>\n<p><code>@api.model_create_multi<\/code> is designed for create overrides that can receive multiple dictionaries in <code>vals_list<\/code>. It allows custom logic to work correctly with batch creation.<\/p>\n<h2>6. Read Operation , Retrieving Existing Records<\/h2>\n<p>The Read operation retrieves information from existing database records.<\/p>\n<p>Odoo provides several ORM methods for accessing records, including:<\/p>\n<ul>\n<li><code>search()<\/code><\/li>\n<li><code>browse()<\/code><\/li>\n<li><code>read()<\/code><\/li>\n<li><code>search_read()<\/code><\/li>\n<li><code>search_count()<\/code><\/li>\n<\/ul>\n<p>Each method serves a slightly different purpose.<\/p>\n<h3>6.1 Using <code>search()<\/code><\/h3>\n<p>The <code>search()<\/code> method retrieves records matching a specified search domain.<\/p>\n<p>Example:<\/p>\n<pre><code>companies = env['res.partner'].search([\r\n    ('is_company', '=', True)\r\n])<\/code><\/pre>\n<p>This searches for contact records marked as companies.<\/p>\n<p>To access the returned records:<\/p>\n<pre><code>for company in companies:\r\n    print(company.name)\r\n    print(company.email)<\/code><\/pre>\n<p>The method returns a recordset, allowing developers to access fields and use other ORM methods.<\/p>\n<h3>6.2 Understanding Search Domains<\/h3>\n<p>A domain is a structured expression used to filter records.<\/p>\n<p>The general structure is:<\/p>\n<pre><code>[\r\n    ('field_name', 'operator', value)\r\n]<\/code><\/pre>\n<p>For example:<\/p>\n<pre><code>companies = env['res.partner'].search([\r\n    ('name', '=', 'ABC Technologies')\r\n])<\/code><\/pre>\n<p>This retrieves records whose name exactly matches <code>ABC Technologies<\/code>.<\/p>\n<p>Some commonly used domain operators include:<\/p>\n<table>\n<tbody>\n<tr>\n<th>Operator<\/th>\n<th>Meaning<\/th>\n<\/tr>\n<tr>\n<td><code>=<\/code><\/td>\n<td>Equal to<\/td>\n<\/tr>\n<tr>\n<td><code>!=<\/code><\/td>\n<td>Not equal to<\/td>\n<\/tr>\n<tr>\n<td><code>&gt;<\/code><\/td>\n<td>Greater than<\/td>\n<\/tr>\n<tr>\n<td><code>&lt;<\/code><\/td>\n<td>Less than<\/td>\n<\/tr>\n<tr>\n<td><code>&gt;=<\/code><\/td>\n<td>Greater than or equal to<\/td>\n<\/tr>\n<tr>\n<td><code>&lt;=<\/code><\/td>\n<td>Less than or equal to<\/td>\n<\/tr>\n<tr>\n<td><code>like<\/code><\/td>\n<td>Case-sensitive substring matching<\/td>\n<\/tr>\n<tr>\n<td><code>ilike<\/code><\/td>\n<td>Case-insensitive substring matching<\/td>\n<\/tr>\n<tr>\n<td><code>=like<\/code><\/td>\n<td>Case-sensitive pattern matching without automatic surrounding wildcards<\/td>\n<\/tr>\n<tr>\n<td><code>=ilike<\/code><\/td>\n<td>Case-insensitive pattern matching without automatic surrounding wildcards<\/td>\n<\/tr>\n<tr>\n<td><code>in<\/code><\/td>\n<td>Matches a value in a list<\/td>\n<\/tr>\n<tr>\n<td><code>not in<\/code><\/td>\n<td>Does not match values in a list<\/td>\n<\/tr>\n<tr>\n<td><code>child_of<\/code><\/td>\n<td>Matches records in a hierarchical relationship<\/td>\n<\/tr>\n<tr>\n<td><code>any<\/code><\/td>\n<td>Matches records with related records satisfying a domain<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>For example:<\/p>\n<pre><code>products = env['product.product'].search([\r\n    ('list_price', '&gt;', 1000)\r\n])<\/code><\/pre>\n<p>This retrieves products whose sales price is greater than 1000.<\/p>\n<h3>Combining Multiple Conditions<\/h3>\n<p>Multiple conditions in a domain are combined using AND by default.<\/p>\n<pre><code>companies = env['res.partner'].search([\r\n    ('is_company', '=', True),\r\n    ('email', '!=', False),\r\n])<\/code><\/pre>\n<p>This retrieves company contacts that have an email address.<\/p>\n<p>Developers can also use logical operators:<\/p>\n<ul>\n<li><code>&amp;<\/code> &#8211; AND<\/li>\n<li><code>|<\/code> &#8211; OR<\/li>\n<li><code>!<\/code> &#8211; NOT<\/li>\n<\/ul>\n<p>These operators use prefix notation. A logical operator appears before the conditions to which it applies.<\/p>\n<p>Example:<\/p>\n<pre><code>records = env['res.partner'].search([\r\n    '|',\r\n    ('name', 'ilike', 'ABC'),\r\n    ('name', 'ilike', 'XYZ'),\r\n])<\/code><\/pre>\n<p>This retrieves records whose names contain either ABC or XYZ.<\/p>\n<p>Another example:<\/p>\n<pre><code>records = env['res.partner'].search([\r\n    '&amp;',\r\n    ('is_company', '=', True),\r\n    ('email', '!=', False),\r\n])<\/code><\/pre>\n<p>This explicitly combines the two conditions using AND.<\/p>\n<h3>6.3 Using <code>browse()<\/code><\/h3>\n<p>The <code>browse()<\/code> method creates a recordset using known database IDs.<\/p>\n<p>Example:<\/p>\n<pre><code>customer = env['res.partner'].browse(15)<\/code><\/pre>\n<p>This returns a recordset representing the customer with ID 15.<\/p>\n<p>Multiple IDs can also be supplied:<\/p>\n<pre><code>customers = env['res.partner'].browse([10, 15, 20])<\/code><\/pre>\n<p>An important distinction is that <code>browse()<\/code> constructs a recordset for the supplied IDs. It does not perform a search using domain conditions.<\/p>\n<p>To check whether the records still exist:<\/p>\n<pre><code>customers = customers.exists()<\/code><\/pre>\n<p><code>exists()<\/code> 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.<\/p>\n<h3>6.4 Using <code>read()<\/code><\/h3>\n<p>The <code>read()<\/code> method retrieves field values from records in a dictionary-based format.<\/p>\n<p>Example:<\/p>\n<pre><code>companies = env['res.partner'].search([\r\n    ('is_company', '=', True)\r\n])\r\n\r\ncompany_data = companies.read([\r\n    'name',\r\n    'email',\r\n    'phone'\r\n])<\/code><\/pre>\n<p>The result is a list of dictionaries containing the requested field values.<\/p>\n<p>For Many2one fields, the traditional read format generally represents the related record as an ID and display-name pair.<\/p>\n<p>For example, a <code>country_id<\/code> value may look like:<\/p>\n<pre><code>(104, 'United States')<\/code><\/pre>\n<p>This format is useful when working with data that needs to be represented as dictionaries rather than recordsets.<\/p>\n<h3>6.5 Using <code>search_read()<\/code><\/h3>\n<p>When both searching and retrieving field values are required, <code>search_read()<\/code> can be convenient.<\/p>\n<p>Example:<\/p>\n<pre><code>company_data = env['res.partner'].search_read(\r\n    [('is_company', '=', True)],\r\n    ['name', 'email', 'phone'],\r\n    limit=10\r\n)<\/code><\/pre>\n<p>This searches for matching companies and returns the requested field values as a list of dictionaries.<\/p>\n<p>It is particularly useful for data retrieval tasks where a recordset is not required.<\/p>\n<h3>6.6 Using <code>search_count()<\/code><\/h3>\n<p>The <code>search_count()<\/code> method returns the number of records matching a domain.<\/p>\n<p>Example:<\/p>\n<pre><code>company_count = env['res.partner'].search_count([\r\n    ('is_company', '=', True)\r\n])<\/code><\/pre>\n<p>Odoo 20 also supports the <code>limit<\/code> parameter:<\/p>\n<pre><code>company_count = env['res.partner'].search_count(\r\n    [('is_company', '=', True)],\r\n    limit=100\r\n)<\/code><\/pre>\n<p>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.<\/p>\n<h3>6.7 Limiting and Sorting Search Results<\/h3>\n<p>The <code>search()<\/code> method supports parameters such as <code>limit<\/code>, <code>offset<\/code>, and <code>order<\/code>.<\/p>\n<p>Example:<\/p>\n<pre><code>companies = env['res.partner'].search(\r\n    [('is_company', '=', True)],\r\n    limit=10,\r\n    order='name asc'\r\n)<\/code><\/pre>\n<p>This retrieves a maximum of ten matching records, sorted by name in ascending order.<\/p>\n<p>These options are useful when working with large datasets.<\/p>\n<h2>7. Working with Recordset Helpers<\/h2>\n<p>Odoo provides several recordset methods that make it easier to filter, transform, sort, and validate records.<\/p>\n<h3>7.1 <code>filtered()<\/code><\/h3>\n<p>The <code>filtered()<\/code> method selects records that satisfy a condition.<\/p>\n<pre><code>companies = env['res.partner'].search([\r\n    ('is_company', '=', True)\r\n])\r\n\r\nactive_companies = companies.filtered(\r\n    lambda partner: partner.active\r\n)<\/code><\/pre>\n<p>This filters the existing recordset and returns only active companies.<\/p>\n<h3>7.2 <code>mapped()<\/code><\/h3>\n<p>The <code>mapped()<\/code> method extracts a field value or applies a function across records.<\/p>\n<p>Example:<\/p>\n<pre><code>company_names = companies.mapped('name')<\/code><\/pre>\n<p>This returns a list of company names.<\/p>\n<p>It can also retrieve related records:<\/p>\n<pre><code>countries = companies.mapped('country_id')<\/code><\/pre>\n<p>This returns a recordset of related countries, with duplicate records removed.<\/p>\n<h3>7.3 <code>sorted()<\/code><\/h3>\n<p>The <code>sorted()<\/code> method returns a recordset ordered by a field or function.<\/p>\n<pre><code>sorted_companies = companies.sorted(\r\n    key=lambda partner: partner.name\r\n)<\/code><\/pre>\n<p>Records are sorted by company name.<\/p>\n<h3>7.4 <code>ensure_one()<\/code><\/h3>\n<p>The <code>ensure_one()<\/code> method verifies that a recordset contains exactly one record.<\/p>\n<pre><code>def update_course(self):\r\n    self.ensure_one()\r\n\r\n    self.write({\r\n        'fee': 6000,\r\n    })<\/code><\/pre>\n<p>If <code>self<\/code> contains zero or multiple records, Odoo raises an error.<\/p>\n<p>This is useful for methods that are designed to work with a single record.<\/p>\n<h3>7.5 <code>exists()<\/code><\/h3>\n<p>The <code>exists()<\/code> method returns the records that still exist in the database.<\/p>\n<pre><code>courses = courses.exists()<\/code><\/pre>\n<p>It is useful when working with recordsets that may contain deleted records.<\/p>\n<p>It should not be treated as an access-rights check.<\/p>\n<h2>8. Update Operation \u2013 Modifying Existing Records<\/h2>\n<p>The Update operation modifies information stored in existing records.<\/p>\n<p>Odoo provides the <code>write()<\/code> method for updating records.<\/p>\n<h3>Syntax<\/h3>\n<pre><code>record.write({\r\n    'field_name': new_value,\r\n})<\/code><\/pre>\n<h3>Example: Updating Customer Information<\/h3>\n<pre><code>customer = env['res.partner'].browse(15)\r\n\r\ncustomer.write({\r\n    'email': 'newemail@example.com',\r\n    'phone': '9999988888',\r\n})<\/code><\/pre>\n<p>This updates the email address and phone number of the customer with ID 15.<\/p>\n<h3>Updating Multiple Records<\/h3>\n<p>The <code>write()<\/code> method can update multiple records in a single operation.<\/p>\n<p>For example, updating a harmless descriptive field:<\/p>\n<pre><code>companies = env['res.partner'].search([\r\n    ('is_company', '=', True)\r\n])\r\n\r\ncompanies.write({\r\n    'comment': 'Reviewed during data cleanup.',\r\n})<\/code><\/pre>\n<p>This updates the comment on all matching company records.<\/p>\n<p>Always review the domain before performing bulk updates, particularly in production databases.<\/p>\n<h3>Updating a Record Using Field Assignment<\/h3>\n<p>Odoo also supports direct field assignment on records.<\/p>\n<pre><code>customer = env['res.partner'].browse(15)\r\n\r\ncustomer.email = 'updated@example.com'<\/code><\/pre>\n<p>This updates the field through the ORM.<\/p>\n<p>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.<\/p>\n<p>For updating several fields together, <code>write()<\/code> is often clearer.<\/p>\n<h2>9. Delete Operation &#8211; Removing Existing Records<\/h2>\n<p>The Delete operation removes existing records from the database.<\/p>\n<p>Odoo provides the <code>unlink()<\/code> method for deleting records.<\/p>\n<h3>Syntax<\/h3>\n<pre><code>record.unlink()<\/code><\/pre>\n<h3>Example: Deleting a Training Course<\/h3>\n<pre><code>course = env['training.course'].browse(15)\r\n\r\ncourse.unlink()<\/code><\/pre>\n<p>This attempts to delete the training course with ID 15.<\/p>\n<h3>Deleting Multiple Records<\/h3>\n<p>The <code>unlink()<\/code> method can also delete multiple records:<\/p>\n<pre><code>courses = env['training.course'].search([\r\n    ('duration', '&lt;=', 0)\r\n])\r\n\r\ncourses.unlink()<\/code><\/pre>\n<p>This attempts to delete all matching courses.<\/p>\n<p>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.<\/p>\n<h3>Archiving Instead of Deleting<\/h3>\n<p>In many business workflows, archiving a record is preferable to permanently deleting it.<\/p>\n<p>For models that support the <code>active<\/code> field, Odoo provides the <code>action_archive()<\/code> method.<\/p>\n<p>Example:<\/p>\n<pre><code>course = env['training.course'].browse(15)\r\n\r\ncourse.action_archive()<\/code><\/pre>\n<p>Archiving makes the record inactive without permanently removing its database entry.<\/p>\n<p>This is useful when business records need to be retained for historical reference.<\/p>\n<h2>10. Working with Relational Fields Using ORM<\/h2>\n<p>Odoo models are connected through relational fields. These relationships allow one record to be associated with other records.<\/p>\n<p>The three main relational field types are Many2one, One2many, and Many2many.<\/p>\n<h3>10.1 Many2one<\/h3>\n<p>A Many2one field connects one record to another record.<\/p>\n<p>For example, multiple sales orders can belong to the same customer.<\/p>\n<pre><code>partner_id = fields.Many2one(\r\n    'res.partner',\r\n    string='Customer'\r\n)<\/code><\/pre>\n<p>To assign an existing customer:<\/p>\n<pre><code>order = env['sale.order'].create({\r\n    'partner_id': 15,\r\n})<\/code><\/pre>\n<p>The value supplied to a Many2one field is the database ID of the related record.<\/p>\n<h3>10.2 One2many<\/h3>\n<p>A One2many field represents multiple related records through an inverse Many2one field.<\/p>\n<p>For example, a sales order contains multiple order lines.<\/p>\n<p>The actual field on Odoo&#8217;s standard <code>sale.order<\/code> model is named <code>order_line<\/code>, not <code>order_line_ids<\/code>.<\/p>\n<p>A simplified field definition looks like:<\/p>\n<pre><code>order_line = fields.One2many(\r\n    'sale.order.line',\r\n    'order_id',\r\n    string='Order Lines'\r\n)<\/code><\/pre>\n<p>The <code>order_id<\/code> field on <code>sale.order.line<\/code> establishes the inverse relationship.<\/p>\n<h3>10.3 Many2many<\/h3>\n<p>A Many2many field connects multiple records to multiple other records.<\/p>\n<p>For example, a training course can have several participants, and a participant can attend multiple courses.<\/p>\n<p>In our custom training model, we can define:<\/p>\n<pre><code>participant_ids = fields.Many2many(\r\n    'res.partner',\r\n    string='Participants'\r\n)<\/code><\/pre>\n<h3>10.4 Understanding <code>fields.Command<\/code><\/h3>\n<p>Odoo provides <code>fields.Command<\/code> to manage One2many and Many2many relationships.<\/p>\n<p>Instead of manually manipulating relationship tables, developers can use these commands.<\/p>\n<table>\n<tbody>\n<tr>\n<th>Command<\/th>\n<th>Purpose<\/th>\n<\/tr>\n<tr>\n<td><code>Command.create()<\/code><\/td>\n<td>Create a related record<\/td>\n<\/tr>\n<tr>\n<td><code>Command.update()<\/code><\/td>\n<td>Update a related record<\/td>\n<\/tr>\n<tr>\n<td><code>Command.delete()<\/code><\/td>\n<td>Delete a related record<\/td>\n<\/tr>\n<tr>\n<td><code>Command.unlink()<\/code><\/td>\n<td>Remove a relationship<\/td>\n<\/tr>\n<tr>\n<td><code>Command.link()<\/code><\/td>\n<td>Add an existing relationship<\/td>\n<\/tr>\n<tr>\n<td><code>Command.clear()<\/code><\/td>\n<td>Remove all relationships<\/td>\n<\/tr>\n<tr>\n<td><code>Command.set()<\/code><\/td>\n<td>Replace relationships with specified records<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<p>Example:<\/p>\n<pre><code>from odoo.fields import Command\r\n\r\ncourse = env['training.course'].create({\r\n    'name': 'Python Development',\r\n    'participant_ids': [\r\n        Command.link(10),\r\n        Command.link(15),\r\n    ],\r\n})<\/code><\/pre>\n<p>This creates a training course and links the existing contacts with IDs 10 and 15 as participants.<\/p>\n<p>Another example:<\/p>\n<pre><code>course.write({\r\n    'participant_ids': [\r\n        Command.create({\r\n            'name': 'New Participant',\r\n        }),\r\n    ],\r\n})<\/code><\/pre>\n<p>For a Many2many field, <code>Command.create()<\/code> creates one related record and links it to the records in the current recordset.<\/p>\n<p>For One2many fields, it creates a related record for each parent record in the recordset.<\/p>\n<h3>Creating a Sales Order with Order Lines<\/h3>\n<p>Relational commands are especially useful when creating complex business records.<\/p>\n<p>For example, a sales order can be created with its order lines in a single ORM operation:<\/p>\n<pre><code>from odoo.fields import Command\r\n\r\norder = env['sale.order'].create({\r\n    'partner_id': 15,\r\n    'order_line': [\r\n        Command.create({\r\n            'product_id': 25,\r\n            'product_uom_qty': 2,\r\n        }),\r\n        Command.create({\r\n            'product_id': 30,\r\n            'product_uom_qty': 1,\r\n        }),\r\n    ],\r\n})<\/code><\/pre>\n<p>This example assumes that the Sales application is installed and the referenced customer and products exist.<\/p>\n<p>Odoo handles the creation of the sales order and its related order lines through the ORM.<\/p>\n<h2>11. Practical Example: Building a Training Management Module<\/h2>\n<p>Now let&#8217;s combine the concepts discussed above in a practical example.<\/p>\n<p>We will create a simple Training Management module that allows internal users to manage course records through the Odoo interface.<\/p>\n<p>The example includes:<\/p>\n<ul>\n<li>A custom model.<\/li>\n<li>CRUD access rights.<\/li>\n<li>List and form views.<\/li>\n<li>A menu and window action.<\/li>\n<li>ORM operations that can be tested through Odoo shell.<\/li>\n<\/ul>\n<h3>Step 1: Create the Module Structure<\/h3>\n<p>Create a custom module named <code>training_management<\/code>.<\/p>\n<pre><code>training_management\/\r\n\u2502\r\n\u251c\u2500\u2500 __init__.py\r\n\u251c\u2500\u2500 __manifest__.py\r\n\u2502\r\n\u251c\u2500\u2500 models\/\r\n\u2502   \u251c\u2500\u2500 __init__.py\r\n\u2502   \u2514\u2500\u2500 training_course.py\r\n\u2502\r\n\u251c\u2500\u2500 security\/\r\n\u2502   \u2514\u2500\u2500 ir.model.access.csv\r\n\u2502\r\n\u2514\u2500\u2500 views\/\r\n    \u2514\u2500\u2500 training_course_views.xml<\/code><\/pre>\n<h3>Step 2: Configure the Manifest<\/h3>\n<p>Create the <code>__manifest__.py<\/code> file:<\/p>\n<pre><code>{\r\n    'name': 'Training Management',\r\n    'version': '1.0',\r\n    'summary': 'Training course management using Odoo ORM',\r\n    'depends': ['base'],\r\n    'data': [\r\n        'security\/ir.model.access.csv',\r\n        'views\/training_course_views.xml',\r\n    ],\r\n    'installable': True,\r\n    'application': True,\r\n    'license': 'LGPL-3',\r\n}<\/code><\/pre>\n<p>The <code>base<\/code> dependency provides the standard Odoo framework and contact model.<\/p>\n<p>The security file is loaded before the views so that the access configuration is available when users interact with the model.<\/p>\n<h3>Step 3: Import the Model<\/h3>\n<p>In the main <code>__init__.py<\/code> file:<\/p>\n<pre><code>from . import models<\/code><\/pre>\n<p>Inside <code>models\/__init__.py<\/code>:<\/p>\n<pre><code>from . import training_course<\/code><\/pre>\n<h3>Step 4: Define the Training Course Model<\/h3>\n<p>Create <code>models\/training_course.py<\/code>:<\/p>\n<pre><code>from odoo import models, fields\r\n\r\n\r\nclass TrainingCourse(models.Model):\r\n\r\n    _name = 'training.course'\r\n    _description = 'Training Course'\r\n\r\n    name = fields.Char(\r\n        string='Course Name',\r\n        required=True\r\n    )\r\n\r\n    duration = fields.Integer(\r\n        string='Duration (Days)'\r\n    )\r\n\r\n    fee = fields.Float(\r\n        string='Course Fee'\r\n    )\r\n\r\n    description = fields.Text(\r\n        string='Description'\r\n    )\r\n\r\n    participant_ids = fields.Many2many(\r\n        'res.partner',\r\n        string='Participants'\r\n    )\r\n\r\n    active = fields.Boolean(\r\n        default=True\r\n    )<\/code><\/pre>\n<p>This creates a custom model with course details, participants, and an active status.<\/p>\n<h3>Step 5: Configure Access Rights<\/h3>\n<p>A custom model does not automatically become accessible to ordinary internal users.<\/p>\n<p>Create the file:<\/p>\n<p><code>security\/ir.model.access.csv<\/code><\/p>\n<p>Add:<\/p>\n<pre><code>id,name,model_id:id,group_id:id,perm_read,perm_write,perm_create,perm_unlink\r\naccess_training_course_user,training.course user,model_training_course,base.group_user,1,1,1,1<\/code><\/pre>\n<p>This grants internal users read, write, create, and delete permissions on the training course model.<\/p>\n<p>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.<\/p>\n<h3>Step 6: Create the Views and Menu<\/h3>\n<p>Create <code>views\/training_course_views.xml<\/code>:<\/p>\n<pre><code>&lt;odoo&gt;\r\n\r\n    &lt;record id=\"view_training_course_list\"\r\n            model=\"ir.ui.view\"&gt;\r\n\r\n        &lt;field name=\"name\"&gt;training.course.list&lt;\/field&gt;\r\n        &lt;field name=\"model\"&gt;training.course&lt;\/field&gt;\r\n\r\n        &lt;field name=\"arch\" type=\"xml\"&gt;\r\n            &lt;list&gt;\r\n                &lt;field name=\"name\"\/&gt;\r\n                &lt;field name=\"duration\"\/&gt;\r\n                &lt;field name=\"fee\"\/&gt;\r\n            &lt;\/list&gt;\r\n        &lt;\/field&gt;\r\n\r\n    &lt;\/record&gt;\r\n\r\n\r\n    &lt;record id=\"view_training_course_form\"\r\n            model=\"ir.ui.view\"&gt;\r\n\r\n        &lt;field name=\"name\"&gt;training.course.form&lt;\/field&gt;\r\n        &lt;field name=\"model\"&gt;training.course&lt;\/field&gt;\r\n\r\n        &lt;field name=\"arch\" type=\"xml\"&gt;\r\n            &lt;form&gt;\r\n                &lt;sheet&gt;\r\n\r\n                    &lt;group&gt;\r\n                        &lt;field name=\"name\"\/&gt;\r\n                        &lt;field name=\"duration\"\/&gt;\r\n                        &lt;field name=\"fee\"\/&gt;\r\n                        &lt;field name=\"active\"\/&gt;\r\n                    &lt;\/group&gt;\r\n\r\n                    &lt;group&gt;\r\n                        &lt;field name=\"participant_ids\"\r\n                               widget=\"many2many_tags\"\/&gt;\r\n                    &lt;\/group&gt;\r\n\r\n                    &lt;group&gt;\r\n                        &lt;field name=\"description\"\/&gt;\r\n                    &lt;\/group&gt;\r\n\r\n                &lt;\/sheet&gt;\r\n            &lt;\/form&gt;\r\n        &lt;\/field&gt;\r\n\r\n    &lt;\/record&gt;\r\n\r\n\r\n    &lt;record id=\"action_training_course\"\r\n            model=\"ir.actions.act_window\"&gt;\r\n\r\n        &lt;field name=\"name\"&gt;Training Courses&lt;\/field&gt;\r\n        &lt;field name=\"res_model\"&gt;training.course&lt;\/field&gt;\r\n        &lt;field name=\"view_mode\"&gt;list,form&lt;\/field&gt;\r\n\r\n    &lt;\/record&gt;\r\n\r\n\r\n    &lt;menuitem id=\"menu_training_root\"\r\n              name=\"Training Management\"\/&gt;\r\n\r\n    &lt;menuitem id=\"menu_training_courses\"\r\n              name=\"Courses\"\r\n              parent=\"menu_training_root\"\r\n              action=\"action_training_course\"\/&gt;\r\n\r\n&lt;\/odoo&gt;<\/code><\/pre>\n<p>The XML file defines:<\/p>\n<ul>\n<li>A list view for displaying courses.<\/li>\n<li>A form view for creating and editing courses.<\/li>\n<li>A window action for opening the model.<\/li>\n<li>A menu entry for accessing the module.<\/li>\n<\/ul>\n<h3>Step 7: Install the Module<\/h3>\n<p>After completing the files:<\/p>\n<ol start=\"1\">\n<li>Restart the Odoo server if required.<\/li>\n<li>Activate Developer Mode.<\/li>\n<li>Navigate to Apps.<\/li>\n<li>Update the Apps List.<\/li>\n<li>Search for Training Management.<\/li>\n<li>Install the module.<\/li>\n<\/ol>\n<p>After installation, internal users with the configured access rights can open the Training Management menu and manage course records.<\/p>\n<h3>Step 8: Test CRUD Operations Using Odoo Shell<\/h3>\n<p>Odoo shell provides an interactive Python environment for testing ORM operations.<\/p>\n<p>Start the shell using the appropriate configuration and database:<\/p>\n<pre><code>.\/odoo-bin shell -c \/path\/to\/odoo.conf -d your_database<\/code><\/pre>\n<p>The exact command may differ depending on the installation method.<\/p>\n<p>Inside the shell, the <code>env<\/code> variable is already available.<\/p>\n<p>Create a course:<\/p>\n<pre><code>course = env['training.course'].create({\r\n    'name': 'Python Development',\r\n    'duration': 30,\r\n    'fee': 5000,\r\n    'description': 'Introduction to Python programming',\r\n})<\/code><\/pre>\n<p>Read course records:<\/p>\n<pre><code>courses = env['training.course'].search([])\r\n\r\nfor course in courses:\r\n    print(course.name, course.duration, course.fee)<\/code><\/pre>\n<p>Update a course:<\/p>\n<pre><code>course.write({\r\n    'fee': 6000,\r\n    'duration': 35,\r\n})<\/code><\/pre>\n<p>Delete a course:<\/p>\n<pre><code>course.unlink()<\/code><\/pre>\n<p>For a safer alternative, archive it:<\/p>\n<pre><code>course.action_archive()<\/code><\/pre>\n<p>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:<\/p>\n<pre><code>env.cr.commit()<\/code><\/pre>\n<p>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.<\/p>\n<h2>12. Advanced ORM Concepts for Odoo Developers<\/h2>\n<p>Beyond the four CRUD operations, Odoo provides additional methods and features for working efficiently with business data.<\/p>\n<h3>12.1 Copying Records with <code>copy()<\/code><\/h3>\n<p>The <code>copy()<\/code> method creates a duplicate of an existing record.<\/p>\n<p>Example:<\/p>\n<pre><code>course = env['training.course'].browse(10)\r\n\r\nnew_course = course.copy({\r\n    'name': 'Advanced Python Development',\r\n})<\/code><\/pre>\n<p>This creates a copy using the original record&#8217;s copyable field values, with the course name overridden.<\/p>\n<p>Fields marked with <code>copy=False<\/code> are not copied in the usual way.<\/p>\n<h3>12.2 Aggregating Records with <code>_read_group()<\/code><\/h3>\n<p>Sometimes developers need aggregated information instead of individual records.<\/p>\n<p>For example, a business may need to calculate total sales by customer or count records by category.<\/p>\n<p>Odoo provides <code>_read_group()<\/code> for backend aggregation.<\/p>\n<p>Example:<\/p>\n<pre><code>results = env['sale.order']._read_group(\r\n    domain=[('state', '=', 'sale')],\r\n    groupby=['partner_id'],\r\n    aggregates=['amount_total:sum'],\r\n)<\/code><\/pre>\n<p>This groups confirmed sales orders by customer and calculates the sum of their total amounts.<\/p>\n<p>The returned structure contains grouped values and aggregate results.<\/p>\n<p>Version note: Odoo&#8217;s ORM changelog records that <code>read_group()<\/code> was deprecated in Odoo 18.2 in favour of <code>_read_group()<\/code> for backend usage and <code>formatted_read_group()<\/code> as a formatted public API. For new backend code in Odoo 20, consult the current <code>_read_group()<\/code> signature and return format.<\/p>\n<h3>12.3 Using Raw SQL Carefully<\/h3>\n<p>Odoo ORM should generally be the first choice for database operations.<\/p>\n<p>Direct SQL bypasses important ORM features such as access rights, record rules, field computations, and cache management.<\/p>\n<p>There are situations where raw SQL may be justified, particularly for specialised database operations or performance-sensitive tasks.<\/p>\n<p>However, developers must keep the ORM cache and database state consistent.<\/p>\n<p>Before executing SQL that depends on pending ORM changes, flush the relevant fields:<\/p>\n<pre><code>self.env['training.course'].flush_model([\r\n    'fee'\r\n])<\/code><\/pre>\n<p>For example, a raw SQL update may look like:<\/p>\n<pre><code>self.env.cr.execute(\r\n    \"\"\"\r\n    UPDATE training_course\r\n    SET fee = %s\r\n    WHERE fee = %s\r\n    \"\"\",\r\n    [6000, 5000]\r\n)<\/code><\/pre>\n<p>After direct SQL updates, invalidate the affected ORM cache:<\/p>\n<pre><code>self.env['training.course'].invalidate_model([\r\n    'fee'\r\n])<\/code><\/pre>\n<p>When direct SQL modifies fields that trigger computed-field dependencies, additional notification through <code>modified()<\/code> may be necessary.<\/p>\n<p>Use parameterized SQL rather than building queries through string concatenation. Never use raw SQL as a shortcut around Odoo&#8217;s security controls.<\/p>\n<h2>13. Important ORM Changes and Practices in Odoo 20<\/h2>\n<p>Odoo&#8217;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.<\/p>\n<h3>13.1 Use <code>domain<\/code> in Search Methods<\/h3>\n<p>Older examples may use the parameter name <code>args<\/code> when defining or calling search-related methods.<\/p>\n<p>The search API uses <code>domain<\/code> as the parameter name in modern Odoo versions.<\/p>\n<p>Prefer:<\/p>\n<pre><code>records = env['res.partner'].search(\r\n    domain=[('is_company', '=', True)]\r\n)<\/code><\/pre>\n<h3>13.2 Use <code>display_name<\/code> Instead of <code>name_get()<\/code><\/h3>\n<p>Older Odoo code commonly used <code>name_get()<\/code> to retrieve display labels for records.<\/p>\n<p>The <code>name_get()<\/code> method was replaced by the <code>display_name<\/code> field in Odoo 17.<\/p>\n<p>For modern code, use:<\/p>\n<pre><code>display_name = record.display_name<\/code><\/pre>\n<p>For custom display-name behaviour, developers should use the appropriate display-name computation mechanism rather than implementing older <code>name_get()<\/code> patterns.<\/p>\n<h3>13.3 Use the Current Aggregation API<\/h3>\n<p>As explained earlier, <code>read_group()<\/code> was deprecated in Odoo 18.2 for backend use.<\/p>\n<p>Odoo 20 developers should use <code>_read_group()<\/code> for backend aggregation and consult the ORM documentation for its current signature and return format.<\/p>\n<h3>13.4 <code>search_count()<\/code> Supports a Limit<\/h3>\n<p>The <code>search_count()<\/code> method accepts a <code>limit<\/code> parameter.<\/p>\n<pre><code>count = env['training.course'].search_count(\r\n    [('active', '=', True)],\r\n    limit=100\r\n)<\/code><\/pre>\n<p>This returns the number of matching records up to the specified limit.<\/p>\n<p>These changes are important when adapting older Odoo code or maintaining custom modules across major versions.<\/p>\n<h2>14. Common ORM Mistakes and How to Avoid Them<\/h2>\n<h3>14.1 Forgetting <code>ensure_one()<\/code><\/h3>\n<p>Some methods are designed to operate on exactly one record.<\/p>\n<p>If they receive a recordset containing multiple records, accessing a field that requires a single record can raise an Expected singleton error.<\/p>\n<p>Use:<\/p>\n<pre><code>def update_course(self):\r\n    self.ensure_one()\r\n\r\n    self.write({\r\n        'fee': 6000,\r\n    })<\/code><\/pre>\n<p>This makes the method&#8217;s single-record requirement explicit.<\/p>\n<h3>14.2 Performing Searches Inside Loops<\/h3>\n<p>Inefficient approach:<\/p>\n<pre><code>for partner in partners:\r\n    orders = env['sale.order'].search([\r\n        ('partner_id', '=', partner.id)\r\n    ])<\/code><\/pre>\n<p>This performs a separate search for every partner.<\/p>\n<p>A better approach is to retrieve the required records together:<\/p>\n<pre><code>orders = env['sale.order'].search([\r\n    ('partner_id', 'in', partners.ids)\r\n])<\/code><\/pre>\n<p>You can then group or filter the results as needed.<\/p>\n<h3>14.3 Reading a Field from a Multi-Record Recordset<\/h3>\n<p>Reading a field directly from a recordset containing multiple records can raise an Expected singleton error.<\/p>\n<p>Incorrect:<\/p>\n<pre><code>print(partners.name)<\/code><\/pre>\n<p>Correct:<\/p>\n<pre><code>for partner in partners:\r\n    print(partner.name)<\/code><\/pre>\n<p>Or use:<\/p>\n<pre><code>names = partners.mapped('name')<\/code><\/pre>\n<h3>14.4 Using <code>sudo()<\/code> Without Understanding Its Impact<\/h3>\n<p><code>sudo()<\/code> changes the access environment and can bypass normal access restrictions.<\/p>\n<p>Incorrect use may expose sensitive records or allow users to modify information they should not access.<\/p>\n<p>Use elevated access only when the business requirement explicitly justifies it, and carefully consider the security implications.<\/p>\n<h2>15. Frequently Asked Questions<\/h2>\n<h3>What is ORM in Odoo?<\/h3>\n<p>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.<\/p>\n<h3>What are CRUD operations in Odoo?<\/h3>\n<p>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.<\/p>\n<h3>What is the difference between <code>search()<\/code> and <code>browse()<\/code>?<\/h3>\n<p><code>search()<\/code> retrieves records matching a specified domain. <code>browse()<\/code> creates a recordset using known database IDs. It does not perform a domain search.<\/p>\n<h3>What is the difference between <code>write()<\/code> and direct field assignment?<\/h3>\n<p>Both update record fields through the ORM. <code>write()<\/code> 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.<\/p>\n<h3>What is <code>self.env<\/code> in Odoo?<\/h3>\n<p><code>self.env<\/code> provides access to the current Odoo environment, including the database cursor, current user, context, company, and model registry.<\/p>\n<h3>What is a recordset?<\/h3>\n<p>A recordset is an ordered collection of records belonging to the same Odoo model. It can contain zero, one, or multiple records.<\/p>\n<h3>What is the purpose of <code>unlink()<\/code>?<\/h3>\n<p><code>unlink()<\/code> deletes records from the database through the ORM, subject to access rights, business restrictions, and relational constraints.<\/p>\n<h3>Can we create multiple records using one <code>create()<\/code> method?<\/h3>\n<p>Yes. Odoo supports batch creation by passing a list of dictionaries to <code>create()<\/code>. When overriding <code>create()<\/code>, developers should use <code>@api.model_create_multi<\/code> to support batch operations correctly.<\/p>\n<h3>What is <code>fields.Command<\/code> used for?<\/h3>\n<p><code>fields.Command<\/code> provides methods for managing One2many and Many2many relationships, including creating, linking, updating, unlinking, and replacing related records.<\/p>\n<h3>What is the difference between <code>read()<\/code> and <code>search_read()<\/code>?<\/h3>\n<p><code>read()<\/code> retrieves field values from an existing recordset. <code>search_read()<\/code> combines searching and reading, returning matching records as dictionaries.<\/p>\n<h3>Why should developers use ORM instead of direct SQL?<\/h3>\n<p>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.<\/p>\n<h2>Conclusion<\/h2>\n<p>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.<\/p>\n<p>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.<\/p>\n<p>By learning <code>create()<\/code>, <code>search()<\/code>, <code>browse()<\/code>, <code>read()<\/code>, <code>search_read()<\/code>, <code>write()<\/code>, and <code>unlink()<\/code>, developers can build efficient and maintainable applications without relying on direct SQL for routine database operations.<\/p>\n<p>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.<\/p>\n<p>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.<\/p>\n<h2>References and Further Reading<\/h2>\n<ol start=\"1\">\n<li><a href=\"https:\/\/www.odoo.com\/documentation\/20.0\/developer\/reference\/backend\/orm.html\" target=\"_blank\" rel=\"noopener\">Odoo 20 \u2013 ORM API<\/a><\/li>\n<li><a href=\"https:\/\/www.odoo.com\/documentation\/20.0\/developer\/reference\/backend\/orm\/changelog.html\" target=\"_blank\" rel=\"noopener\">Odoo 20 \u2013 ORM Changelog<\/a><\/li>\n<li><a href=\"https:\/\/www.odoo.com\/documentation\/20.0\/developer\/tutorials\/server_framework_101\/04_securityintro.html\" target=\"_blank\" rel=\"noopener\">Odoo 20 \u2013 Security: Access Rights<\/a><\/li>\n<li><a href=\"https:\/\/www.odoo.com\/documentation\/20.0\/developer\/tutorials.html\" target=\"_blank\" rel=\"noopener\">Odoo 20 \u2013 Backend Developer Tutorials<\/a><\/li>\n<\/ol>\n","protected":false},"excerpt":{"rendered":"<p>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 [&hellip;]<\/p>\n","protected":false},"author":5,"featured_media":10187,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"_jetpack_memberships_contains_paywalled_content":false,"_jetpack_hide_featured_image":false,"_jetpack_featured_image_duplicate_dismissed":0,"_jetpack_memberships_contains_paid_content":false,"footnotes":""},"categories":[325,195],"tags":[],"class_list":["post-10186","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-odoo-20","category-odoo-customization"],"jetpack_sharing_enabled":true,"jetpack_featured_media_url":"https:\/\/machinser.com\/wp-content\/uploads\/2026\/11\/Odoo-ORM-and-CRUD-Guide.png","_links":{"self":[{"href":"https:\/\/machinser.com\/ar\/wp-json\/wp\/v2\/posts\/10186","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/machinser.com\/ar\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/machinser.com\/ar\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/machinser.com\/ar\/wp-json\/wp\/v2\/users\/5"}],"replies":[{"embeddable":true,"href":"https:\/\/machinser.com\/ar\/wp-json\/wp\/v2\/comments?post=10186"}],"version-history":[{"count":2,"href":"https:\/\/machinser.com\/ar\/wp-json\/wp\/v2\/posts\/10186\/revisions"}],"predecessor-version":[{"id":10189,"href":"https:\/\/machinser.com\/ar\/wp-json\/wp\/v2\/posts\/10186\/revisions\/10189"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/machinser.com\/ar\/wp-json\/wp\/v2\/media\/10187"}],"wp:attachment":[{"href":"https:\/\/machinser.com\/ar\/wp-json\/wp\/v2\/media?parent=10186"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/machinser.com\/ar\/wp-json\/wp\/v2\/categories?post=10186"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/machinser.com\/ar\/wp-json\/wp\/v2\/tags?post=10186"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}