How to Add a One2many Field in Odoo

Abid Patel
03-Sep-2024 Updated : 03-Sep-2024

Learn how to efficiently add a One2many field in Odoo, enhancing data relationships and user interface. This guide walks you through the steps for seamless integration.

How to Add a One2many Field in Odoo

Odoo is a versatile and powerful ERP platform that allows businesses to manage various operations efficiently. One of the core features of Odoo is its ability to establish relationships between different models, which is essential for creating a dynamic and interconnected database. One such relationship is the One2many field, which allows a single record in one model to be associated with multiple records in another model. In this blog post, we will guide you through the process of adding a One2many field in Odoo, explaining each step in detail.

Understanding the One2many Field

Before diving into the implementation, it’s important to understand what a One2many field is and how it functions within Odoo.

What is a One2many Field?

A One2many field in Odoo represents a one-to-many relationship between two models. This means that a single record from one model can be linked to multiple records from another model. For example, in an order model, a single order can have multiple order lines, creating a one-to-many relationship between the order and its lines.

Why Use a One2many Field?

The One2many field is crucial for managing related records efficiently. It enables you to group related data together, making it easier to manage and visualize. For example, when creating an invoice, you might use a One2many field to list all the items included in that invoice. This not only makes the data more organized but also enhances the user experience by providing a comprehensive view of related information in a single interface.

1. Define the One2many Field in the Model

The first step in adding a One2many field in Odoo is to define it in the corresponding model. This involves modifying the Python model file where the field will be used.

Example Scenario

Let’s say we are working with a model called 'school.class', and we want to add a One2many field that links each class to multiple students. We will create a One2many field that links the 'school.class' model to the 'school.student' model.

Defining the Field

First, locate the model file where you want to add the One2many field. Typically, this file will be in the 'models' directory of your custom Odoo module.

Here is how you can define a One2many field in the 'school.class' model:

python

from odoo import models, fields

class SchoolClass(models.Model):
    _name = 'school.class'
    _description = 'Class'

    name = fields.Char(string='Class Name', required=True)
    student_ids = fields.One2many('school.student', 'class_id', string='Students')

Explanation:

'student_ids': This is the name of the One2many field we are adding. It’s a common practice to name One2many fields with an '_id' suffix.

'school.student': This is the name of the related model that the One2many field will reference. In this case, it refers to the 'school.student' model.

'class_id': This is the Many2one field in the 'school.student' model that links the student to a class.

'string='Students': This defines the label that will be shown in the UI for this field.

With this code, the 'student_ids' field will allow you to manage multiple student records from within a single class record.

2. Define the Corresponding Many2one Field in the Related Model

For the One2many relationship to work, you need to define a corresponding Many2one field in the related model. This Many2one field will link the related model back to the main model.

Example of Defining the Many2one Field

Let’s define the 'class_id' Many2one field in the 'school.student' model, which will link the student to a specific class.

Here’s how you can do it:

python

from odoo import models, fields

class Student(models.Model):
    _name = 'school.student'
    _description = 'Student'

    name = fields.Char(string='Student Name', required=True)
    age = fields.Integer(string='Age')
    class_id = fields.Many2one('school.class', string='Class')

Explanation:

'class_id': This Many2one field creates the reverse link from the 'school.student' model to the 'school.class' model. It’s essential for establishing the One2many relationship.

With the 'class_id' field defined, each student can now be linked to a class, and the 'student_ids' field in the 'school.class' model will automatically manage this relationship.

3. Update the View to Include the One2many Field

Once you’ve defined the One2many field in the model, the next step is to update the view to include this field. This involves modifying the XML file that defines the form or tree views for the model.

Example of Updating the Form View

Let’s update the class form view to include the 'student_ids' One2many field..

Here’s how you can do it:

xml

<record id="view_class_form" model="ir.ui.view">
    <field name="name">class.form</field>
    <field name="model">school.class</field>
    <field name="arch" type="xml">
        <form string="Class">
            <sheet>
                <group>
                    <field name="name"/>
                    <field name="student_ids">
                        <tree string="Students">
                            <field name="name"/>
                            <field name="age"/>
                        </tree>
                    </field>
                </group>
            </sheet>
        </form>
    </field>
</record>

Explanation:

'': This line adds the 'student_ids' field to the class form view, allowing users to manage student records directly from the class form.

'': This defines a tree view within the form view to display the related student records. It includes the 'name' and 'age' fields from the 'school.student' model.

With this XML code, the 'student_ids' field will now appear in the class form view, allowing you to add, remove, or edit student records associated with a class.

4: Adding the One2many Field to Tree View (Optional)

In addition to the form view, you might also want to display the One2many field in a tree view (list view) for better data visualization.

Example of Updating the Tree View

Here’s how you can include the 'student_ids' field in the class tree view:

xml

<record id="view_class_tree" model="ir.ui.view">
    <field name="name">class.tree</field>
    <field name="model">school.class</field>
    <field name="arch" type="xml">
        <tree string="Classes">
            <field name="name"/>
            <field name="student_ids" widget="many2many_tags"/>
        </tree>
    </field>
</record>

Explanation:

'': This line adds the 'student_ids' field to the class tree view using the 'many2many_tags' widget, which provides a concise display of the related student records.

5: Testing the Implementation

After defining the One2many field and updating the views, the next step is to test your implementation to ensure everything works as expected.

Restart the Odoo Server

To apply your changes, restart the Odoo server. Once restarted, navigate to the relevant menu in the Odoo interface to check if the One2many field is functioning correctly.

Create and Test Records

Create a few records in the 'school.class' model, then add student records using the One2many field in the class form view. You should now be able to manage multiple student records directly from within the class record.

Verify Data Integrity

Ensure that the student records are correctly linked to the class and that the relationship is reflected in both the class and student models.

6: Enhancing the One2many Field (Optional)

To provide a better user experience, you can enhance the One2many field with additional features, such as adding constraints, using context to prefill fields, and providing inline editing capabilities.

Adding Constraints to the One2many Field

You can add constraints to the One2many field to ensure data integrity. For example, you might want to ensure that a student can only be linked to one class.

python

from odoo.exceptions import ValidationError

class SchoolClass(models.Model):
    _name = 'school.class'
    _description = 'Class'

    name = fields.Char(string='Class Name', required=True)
    student_ids = fields.One2many('school.student', 'class_id', string='Students')

    @api.constrains('student_ids')
    def _check_student_class(self):
        for record in self:
            if len(record.student_ids) > 30:
                raise ValidationError("A class can't have more than 30 students
Providing Inline Editing Capabilities

Odoo allows for inline editing of One2many fields, which can greatly enhance the user experience. To enable inline editing, you can add the 'editable' attribute to the One2many field in the XML view:

xml

<field name="student_ids" widget="one2many_list" mode="tree,form" editable="bottom"/>

Explanation:

'editable="bottom"': This attribute allows users to add new student records directly in the One2many list view at the bottom of the list.

Inline editing makes it easier to manage related records without navigating away from the parent record.

7. Conclusion

Adding a One2many field in Odoo is a powerful way to manage related records and create dynamic, interconnected databases. By following the steps outlined in this blog, you can successfully implement a One2many field in your custom Odoo modules, providing users with the ability to manage multiple related records seamlessly.

Whether you’re building a simple application or a complex ERP solution, understanding how to use One2many fields effectively is crucial for creating a robust and efficient system. By defining the field in the model, updating the views, and testing the implementation, you can ensure that your One2many fields are correctly integrated and ready for use.

As you continue to develop in Odoo, you’ll find that One2many fields are just one of many powerful tools at your disposal. With practice and experience, you’ll be able to leverage these fields to create even more sophisticated and dynamic applications.


This blog post provides a comprehensive guide to adding a One2many field in Odoo, covering all essential steps while ensuring the content remains relevant and informative for developers at all levels.

Make a Comment

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