Enable Dark Mode!
how-to-create-orm-method-in-odoo-19.jpg
By: Arjun V P

How to Create() orm method in Odoo 19

Technical Odoo 19 Odoo Enterprises Odoo Community

One of the basic Odoo methods for adding new records to the database is the create() ORM method. Developers can add data to database tables using this method without having to write SQL queries. Because it manages relational fields, computed fields, and record creation with automatic validation, the create() method is crucial for any Odoo developer.

What is the Create() method?

To add new records to a model, use the create() method. After inserting the data into the database and returning the newly created record or records, it takes a dictionary (or list of dictionaries) containing field names and their values.

Syntax:

Model.create(vals)

Parameters:

  • vals: A dictionary containing field values, or a list of dictionaries for multiple records.

Returns: A recordset containing the newly created record(s).

Creating a Single Record Using create()

Using a dictionary of field values to create a single record is the most popular use of the create() method. A field name is represented by each key in the dictionary, and the data to be stored is represented by the corresponding value.

Example: Creating a Customer

customer = self.env['res.partner'].create({
    'name': 'John C',
    'email': 'john.c@example.com',
    'phone': '2255',
    'customer_rank': 1,
})

This will create a new customer record in the res.partner model and return a recordset containing the newly created partner.

Overriding the create() Method in Odoo 19

Developers frequently have to modify record creation logic in real-world applications. A custom module's create() method can be overridden to accomplish this.

To effectively support batch creation in Odoo 19, it is highly advised to use the @api.model_create_multi decorator.

Example: Basic create() Override

from odoo import api, models
class ResPartner(models.Model):
    _inherit = 'res.partner'
    @api.model_create_multi
    def create(self, vals_list):
        for vals in vals_list:
            if not vals.get('email'):
                vals['email'] = 'default@example.com'
        return super().create(vals_list)

This example assigns a default email if none is provided before the record is created.

Automatically Creating a Contact for a Company

In many business situations, a company should always have at least one contact person. This should be addressed after creating the company record. Use a context flag to prevent recursion.

Example: Auto-create Contact If None Exists

@api.model_create_multi
def create(self, vals_list):
    if self.env.context.get('skip_auto_contact'):
        return super().create(vals_list)
    partners = super().create(vals_list)
    for partner in partners:
        if partner.is_company:
            has_contact = partner.child_ids.filtered(lambda c: c.type == 'contact')
            if not has_contact:
                self.env['res.partner'].with_context(
                    skip_auto_contact=True
                ).create({
                    'name': partner.name or 'Primary Contact',
                    'parent_id': partner.id,
                    'type': 'contact',
                    'email': partner.email,
                    'phone': partner.phone,
                })
    return partners

This approach is safe, avoids infinite recursion, and ensures data consistency

Creating Multiple Records in a Single create() Call

Odoo ORM is designed to handle batch operations efficiently. Instead of calling create() multiple times inside a loop, developers should pass a list of dictionaries to create multiple records in one call. This approach improves performance and reduces unnecessary database queries.

Example: Creating Multiple Records

partners = self.env['res.partner'].create([
    {'name': 'Alice', 'email': 'alice@example.com'},
    {'name': 'Bob', 'email': 'bob@example.com'},
])

Using batch creation is highly recommended in Odoo 19, especially when importing data or creating records programmatically in bulk.

Validations Inside the create() Method

One of the most common real-world requirements is enforcing business rules at the time of record creation. The create() method is an ideal place to add such validations because it runs before the data is permanently stored.

Example: Prevent Creating a Partner Without a Name

from odoo import api, models
from odoo.exceptions import ValidationError
class ResPartner(models.Model):
    _inherit = 'res.partner'
    @api.model_create_multi
    def create(self, vals_list):
        for vals in vals_list:
            if not vals.get('name'):
                raise ValidationError("Partner name is required.")
        return super().create(vals_list)

This ensures that invalid records never enter the database, improving overall data quality.

Best Practices When Using create() in Odoo 19

Maintaining performance, readability, and data integrity when using Odoo 19's create() ORM method requires adhering to best practices. Even when creating a single record, developers should always use the @api.model_create_multi decorator to guarantee effective batch processing. The logic in the create() method should be kept simple and limited to actions that are necessary during the creation of a record, like enforcing validations or setting defaults. Batch creation should be preferred over repeated create() calls inside loops to minimize database overhead, and early validation helps prevent incorrect data from being saved. Additionally, context flags should be used carefully when creating related records within create() to prevent unintended side effects and infinite recursion.

Conclusion

A key component of Odoo 19's backend development is the create() ORM method, which provides a strong and adaptable means of managing the addition of records to the system. Create() gives developers the ability to enforce business rules and preserve data consistency from the outset, from simple record creation to sophisticated customization via method overriding, batch operations, and validation logic. Developers can create scalable, effective, and maintainable Odoo applications by adhering to suggested patterns like utilizing @api.model_create_multi, supporting bulk operations, and validating data early. Thus, mastering the create() method is essential to creating Odoo modules that are clear and ready for production.

To read more about What are ORM Methods in Odoo 18, refer to our blog What are ORM Methods in Odoo 18.


If you need any assistance in odoo, we are online, please chat with us.



0
Comments



Leave a comment



Recent Posts

whatsapp_icon
location

Calicut

Cybrosys Technologies Pvt. Ltd.
Neospace, Kinfra Techno Park
Kakkancherry, Calicut
Kerala, India - 673635

location

Kochi

Cybrosys Technologies Pvt. Ltd.
1st Floor, Thapasya Building,
Infopark, Kakkanad,
Kochi, India - 682030.

location

Bangalore

Cybrosys Techno Solutions
The Estate, 8th Floor,
Dickenson Road,
Bangalore, India - 560042

Send Us A Message