Skip to content

Instantly share code, notes, and snippets.

@CakJuice
Last active October 8, 2022 18:00
Show Gist options
  • Save CakJuice/fcc3bcdb3d20457b31fdef0e56466c47 to your computer and use it in GitHub Desktop.
Save CakJuice/fcc3bcdb3d20457b31fdef0e56466c47 to your computer and use it in GitHub Desktop.
Example code for Many2one & One2many fields
from odoo import models, fields
class ParentModel(models.Model):
_name = 'parent.model'
parent_field_1 = fields.Char(string="Parent Field 1")
parent_field_2 = fields.Integer(string="Parent Field 2")
# If you want to display child data, you must create One2many field.
# The One2many field used for inverse field from Many2one field
child_field_ids = fields.One2many('child.model', 'parent_field_id', string="Child IDS")
class ChildModel(models.Model):
_name = 'child.model'
child_field_1 = fields.Char(string="Child Field 1")
child_field_2 = fields.Integer(string="Child Field 2")
child_field_3 = fields.Boolean(string="Child Field 3")
parent_field_id = fields.Many2one('parent.model', string="Parent ID")
<odoo>
<record model="ir.ui.view" id="view_parent_form">
<field name="name">parent.model.form</field>
<field name="model">parent.model</field>
<field name="arch" type="xml">
<form>
<sheet>
<group>
<field name="parent_field_1"/>
<field name="parent_field_2"/>
</group>
<notebook>
<page string="Child Data">
<!-- you can display child data like code below -->
<field name="child_field_ids">
<tree>
<field name="child_field_1"/>
<field name="child_field_2"/>
<field name="child_field_3"/>
</tree>
</field>
</page>
</notebook>
</sheet>
</form>
</field>
</record>
</odoo>
@CakJuice
Copy link
Author

CakJuice commented Sep 21, 2018

why you display "child" in dropdown? "child" should display in tree view because "parent" is One2many to "child". It means one "parent" have many "child", right?
so if you choose some "parent" it will display all "child" automatically on parent form.

from your image, i think you want to use 3 model, right? Parent -> Many2one -> Child -> One2many -> GrandChild

@Gelson15
Copy link

OK, let's imagine that we want to choose Parent, so that shows us the list of the children in our tree. and that's what I want.

@Gelson15
Copy link

Gelson15 commented Sep 21, 2018

I already understand the relationship
my goal and populate the tree automatically

@D0nmoses
Copy link

Hey @Gelson15 . Were you able to find a way to automatically populate a One2many tree view?

@madrara256
Copy link

I am also looking for a similar solution, If anyone has found an answer to this please share

@MuhammadNsearaty
Copy link

in my project I have the same relation and it's working fine
but when I delete the child record from the parent tree view (for example) it's being deleted from the database :(

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment