How to Create One2Many Fields in Odoo

One2Many fields is a fields is declaration of a one-to-many relationship between two models (which also called database table). It allows us to create a link between records of one model to multiple records in another model.

The best example which we use everyday in Odoo is One2many fields of order_line in sale.order model.

One2Many Fields example in Odoo
One2Many fields in Sale Order menu. Screen captured from Odoo

This article will going to break down a simple declaration of a one2Many field in a custom module. Let’s say we want to create a one2Many fields into our module. We can just simply declare it like this

We are now seeing the bigger picture of the simplest one2Many field declaration. Let’s break it down

class MainModels(models.Model):

 This one is standard class declaration in Odoo. We declare a class with the name of MainModels, which is basically inheriting models.Model framework from Odoo.

_name = "main.models"

We are now declaring a database table with the name of main.models

the_field = fields.One2many("comodels.of.main", "model_id")

Here, is the declaration of the field. This field is similar to order_line in sale.order module that holds other fields. You also notice that there’s “comodels.of.main” upon declaration of this field, right? It is basically the second models which declared in other class and we connect it through the_field declaration.

class ComodelsOfMain(models.Model):

Same with the first one, this is the declaration of the second field. if we use the same example to sale.order module from the picture above, this class is the place where the “Product”, “Barcode”, “Description”, “Quantity” etc. are defined and later be called through .xml.

_name = 'comodels.of.main'

Here we are declaring a database table with the name of comodels.of.main.

model_id = fields.Many2one('main.models')

 This final fields is a declaration of ID that is related to the main,models. In the database terms, this fields is a foreign key.

Assuming that you are already defining things such as the XML views in your custom module, you can then simply define the_field into your XML file by typing in :

<field name = "the field" />

You should later will be able to see your simple One2many field into your custom module, and we are also already finished the tutorial on how to define One2Many fields in Odoo.

Then, how about Inheriting existence models and put the One2Many fields into it?

Well, that’s simple. In this scenario, let’s assume that we are going to create a custom One2Many field called “Item Quality Number” that later will show in the Product Template (Inventory Module). You can simply define things like this :


Leave a Reply

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