
Learn how to use the create ORM method in Odoo to add new records efficiently, including custom logic and bulk creation.
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.
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:
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".
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:
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 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:
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.
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.
Your email address will not be published. Required fields are marked *