Overview
In Odoo, XML is widely used to load initial data, configure defaults, and manage master records. It allows developers to predefine datasets that can include relational fields, which are critical for linking models together. This tutorial explains how to create XML datasets and implement Many2one, One2many, and Many2many relationships correctly.
1. Basic XML Structure for Odoo Data
An XML record in Odoo follows this pattern:
<record id="external_id" model="model.name">
<field name="field_name">value</field>
</record>
To load the XML file, include it in your module's __manifest__.py:
'data': [
'data/your_file.xml',
],
To prevent the data from being deleted during upgrades, wrap the XML in:
<odoo noupdate="1">
2. Example Models
class SchoolClass(models.Model):
_name = 'school.class'
name = fields.Char(string='Class')
class SchoolStudent(models.Model):
_name = 'school.student'
name = fields.Char(string='Student')
class_id = fields.Many2one('school.class')
subject_ids = fields.Many2many('school.subject')
class SchoolSubject(models.Model):
_name = 'school.subject'
name = fields.Char(string='Subject')
3. Many2one Implementation in XML
Many2one stores a single foreign key reference.
Python Field
class_id = fields.Many2one('school.class')
XML
Create the referenced record first:
<record id="class_a" model="school.class">
<field name="name">Class A</field>
</record>
Assign the student to the class:
<record id="student_1" model="school.student">
<field name="name">John</field>
<field name="class_id" ref="class_a"/>
</record>
4. Many2many Implementation in XML
Many2many fields store multiple linked records.
Python Field
subject_ids = fields.Many2many('school.subject')
Create Subjects First
<record id="subject_math" model="school.subject">
<field name="name">Math</field>
</record>
<record id="subject_physics" model="school.subject">
<field name="name">Physics</field>
</record>
Assign to Student
<record id="student_1" model="school.student">
<field name="subject_ids" eval="[
(6, 0, [ref('subject_math'),
ref('subject_physics')])]" />
</record>
5. One2many Implementation in XML
One2many is the inverse of Many2one. The relation is stored in the Many2one field.
Python Field
class_id = fields.Many2one('school.class')
student_ids = fields.One2many('school.student', 'class_id')
Method 1 (Recommended)
Set the Many2one only:
<record id="student_2" model="school.student">
<field name="name">Anna</field>
<field name="class_id" ref="class_a"/>
</record>
One2many updates automatically.
Method 2 (Directly from One2many)
<record id="class_b" model="school.class">
<field name="name">Class B</field>
<field name="student_ids" eval="[
(0,0,{'name':'David'}),
(0,0,{'name':'Maria'})]"/>
</record>
