Odoo, a powerful and versatile business application framework, provides a comprehensive Object-Relational Mapping (ORM) layer that simplifies database operations. The ORM methods offered by Odoo enable developers to interact with the database effortlessly, perform data manipulations, and build robust applications. In this blog post, we will explore the fundamental concepts of ORM methods in Odoo and how they contribute to efficient and streamlined database management.
ORM methods in Odoo offer a higher-level abstraction for interacting with the database, eliminating the need to write complex SQL queries manually. These methods encapsulate common database operations, such as creating, reading, updating, and deleting records, and provide a user-friendly interface to work with the data. Some of the commonly used ORM methods in Odoo include:
* create(): Model.create(vals_list)
This method is used to create a new record in the database. It takes a dictionary of field-value pairs representing the data to be stored.
wo_details = self.env['workorder.details'].create({
'operation': wo_number_id.name,
'employee_code': emp_code,
'name': emp_name,
'company': company_id.id,
'reference': wo_number_id.reference,
'status': [(6, 0, start_tag.ids)],
})
self.env['workorder.details']: This is how we access the model workorder.details through the Odoo environment's registry.
.create({...}): This is the create method that's called on the workorder.details model. It takes a dictionary as an argument, where keys represent field names and values represent the values we want to assign to those fields in the new record.
After creating the dictionary with field-value pairs, the create method will insert a new record into the workorder.details model with the specified values. The variable wo_details will hold the newly created record.
* copy() :Model.copy(default = None)The copy method creates a new record that is an exact duplicate of the original record.
product_duplicate = product.copy({'name': 'Duplicate'})
.copy({'name': 'Duplicate'}): This is the copy method being called on the product record. The dictionary {'name': 'Duplicate'} contains the field we want to update and its new value. In this case, we are creating a duplicate of the product record and setting the 'name' field of the duplicate to 'Duplicate'.* flush():Model.flush(fnames=None, records=None)The flush method is used to handle pending calculations and updates on records in a model. It's particularly useful when you want to ensure that any pending changes are reflected in the database.
self.env['account.move.line'].flush(['account_id', 'journal_id'])
.flush(['account_id', 'journal_id']): This is the flush method being called on the account.move.line model. The list ['account_id', 'journal_id'] contains the names of fields for which we want to handle pending calculations and updates.* search(): This method is used to search for records based on specified criteria. It returns a list of record ids matching the search criteria.
customer = self.env['res.partner'].search([('id', '=', rec.partner_id.id)])
.search([...]): This is the search method being called on the res.partner model. It takes a domain as its argument, which specifies the search conditions.[('id', '=', rec.partner_id.id)]: This is the domain used for the search. It's a list containing a single tuple. The tuple specifies the condition to be applied to the search. In this case, we are searching for records where the field 'id' (which is the primary key of the record) matches the id of rec.partner_id.* browse(): This method is used to retrieve records from the database based on their IDs. It returns a recordset that represents the matched records.
partner = self.env['res.partner'].browse(partner_id)
.browse(partner_id): This is the browse method being called on the res.partner model. The argument partner_id is the ID of the specific record we want to retrieve.* read(): This method is used to retrieve the field values of one or more records. It takes a list of record IDs and a list of field names to read.
self.env['mail.channel'].browse(self.group_groups.id).read()
.browse(self.group_groups.id): This uses the browse method to retrieve a record from the mail.channel model based on the provided group_groups.id and self.group_groups.id is used to access the ID of the record..read(): This is the read method being called on the retrieved record. Since the read method does not require any arguments, it will read the default fields defined for the record.* write(): This method is used to update the field values of one or more records. It takes a dictionary of field-value pairs to update.
self.write({'state': done})
.write({'state': 'done'}): This is the write method being called on the current record(s). The dictionary {'state': 'done'} specifies the field we want to update and its new value. In this case, we are updating the field named 'state' with the value 'done'.* unlink(): This method is used to delete one or more records from the database.
self.env['mail.channel'].browse(self.group_private.id).unlink()
.browse(self.group_private.id): This uses the browse method to retrieve a specific record from the mail.channel model based on the provided group_private.id and self.group_private.id is used to access the ID of the record.unlink(): This is the unlink method being called on the retrieved record. The unlink method doesn't require any arguments. It directly deletes the record from the database.* Map : Model.mapped(func)The mapped method iterates over each record in the source_recordset, applies the provided func function, and collects the results in a new recordset (result_recordset). invoices = self.mapped('invoice_ids')
* Sort : Model.sorted(key=None, reverse=False) Returns a self-ordered Recordset with the key. self.line_ids = self.line_ids.sorted(key=lambda x: x.product_id.name)
Benefits of ORM Methods in Odoo:
1. Simplified Database Operations: ORM methods provide a simplified and intuitive approach to perform common database operations without writing complex SQL queries.2. Portability and Compatibility: By using ORM methods, the code becomes more portable and compatible across database backend3. Enhanced Readability and Maintainability: ORM methods enhance the readability and maintainability of the code by providing a consistent and standardized way of interacting with the database.4. Data Integrity and Security: The ORM layer in Odoo ensures data integrity and security by handling database transactions, enforcing referential integrity, and providing access control mechanisms.