I have two models defined in Odoo. The first model has an ID which automatically created by Odoo when i created a record in it. And then, I need to "link" that ID into my second models once i create it, with the name of main_id
. This main_id
will act as foreign key in second model.
I see that same approach is achieved between Odoo's product.template
and product.product
through psql
. I can use One2Many to achieve this way, but i don't know how to define the field in Odoo to achieve main_id
column that linked to id
because i don't define the id
by myself.
My First Model :
class FirstModel(models.Model):
_name = 'first.model'
user = fields.Many2one("res.user", "Person Name")
product_lines = fields.One2many('first.model.lines', 'product_id')
My Second Model :
class SecondModel(models.Model):
_name = 'first.model.lines'
product_id = fields.Many2one('product.product', string="Product Name")
product_qty = fields.Integer(string="Qty")
How can I create record in the second model that later has the First Model id as foreign key?
I found the solution for creating a "Foreign Key" in One2many.
When creating One2many, as Odoo documentation stated it needs something called inverse_name
. It should be declared in first model and also the second model. Instead using 'product_id'
, i create a new variable named 'foreign_key'
that later will connect both model as it supposed be.
So the FirstModel would be :
class FirstModel(models.Model):
_name = 'first.model'
user = fields.Many2one("res.user", "Person Name")
product_lines = fields.One2many('first.model.lines', 'foreign_key')
and the SecondModel will be :
class SecondModel(models.Model):
_name = 'first.model.lines'
foreign_key = fields.Many2one('combine.product', string="Foreign Key")
product_id = fields.Many2one('product.product', string="Product Name")
product_qty = fields.Integer(string="Qty")
As addition, since foreign_key
will be automatically added by Odoo, inside .XML files, i hide that foreign_key
field so user will not notice and doing things on it.
My XML file :
<field name="product_lines">
<tree>
<field name="foreign_key" invisible="1"/>
<field name="product_id"/>
<field name="product_qty"/>
</tree>
</field>