Create ORM Method in Odoo

Abid Patel
26-Oct-2024 Updated : 26-Oct-2024

Learn how to use the create ORM method in Odoo to add new records efficiently, including custom logic and bulk creation.

Create ORM Method in Odoo

The create method in Odoo is an essential function that allows developers to insert new records into the database using the Odoo Object-Relational Mapping (ORM) system. This method is commonly used across various models and provides a straightforward way to add new entries with specific field values.

Basic Usage of the Create Method

To use the create method, you need to call it on the desired model, passing a dictionary that contains the field names and their corresponding values. Here's a basic example of creating a new partner in the res.partner model:

python
self.env['res.partner'].create({
    'name': 'John Doe',
    'email': 'johndoe@example.com',
})

In this example, a new partner record is created with the name "John Doe" and the email "johndoe@example.com".

Overriding the Create Method

You can also override the create method to implement custom logic before the record is created. This is particularly useful for adding validations or setting default values. Below is an example that checks if the email format is valid before creating a record:

python
from odoo import models, api
from odoo.exceptions import ValidationError

class CustomPartner(models.Model):
    _inherit = 'res.partner'

    @api.model
    def create(self, vals):
        if 'email' in vals and not vals['email'].endswith('@example.com'):
            raise ValidationError("Email must end with @example.com")
        return super(CustomPartner, self).create(vals)

In this example:

  • ▹ The create method is overridden in the CustomPartner class.
  • ▹ A validation check is added to ensure the email ends with @example.com.
  • ▹ If the check fails, a ValidationError is raised, preventing the record from being created.

Bulk Record Creation

The create method can also be used to create multiple records at once. You can achieve this by passing a list of dictionaries to the create method. Here’s an example:

python
partners = [
    {'name': 'Alice Smith', 'email': 'alice@example.com'},
    {'name': 'Bob Johnson', 'email': 'bob@example.com'},
]

self.env['res.partner'].create(partners)

This will create two new partner records in a single call, making it efficient when adding multiple records.

Conclusion

The create method is a powerful tool in Odoo that simplifies the process of adding new records to the database. By understanding how to use and override this method, developers can implement custom logic, validation, and create multiple records efficiently.

Make a Comment

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