Odoo documentation is very limited and finding help is further scary. I am sharing a quick tip on how to get a value into the current working model from a different model
There are two ways to access a field from a different model file in Odoo 16:
1. Using a Many2one field:
This is the most common way to access a field from a different model file.
For example, let's say you have two models: Customer
and Product
. The Customer
model has a product_id
field, which is a Many2one field that references the Product
model.
To access the product_name
field from the Product
model in the Customer
model, you would use the following code:
Python
class Customer(models.Model):
_name = 'res.partner'
product_id = fields.Many2one('product.product', 'Product')
product_name = fields.Char(compute='_compute_product_name')
@api.depends('product_id')
def _compute_product_name(self):
for customer in self:
if customer.product_id:
customer.product_name = customer.product_id.name
This code will create a new field called product_name on the Customer model, which will be populated with the value of the name field on the Product model.
2. Using a Related field:
A Related field allows you to access a field from another model without having to create a Many2one field.
For example, let's say you have the same two models as above, but you don't want to create a Many2one field on the Customer
model.
To access the product_name
field from the Product
model in the Customer
model using a Related field, you would use the following code:
Python
class Customer(models.Model):
_name = 'res.partner'
product_name = fields.Related('product_id', 'name')
This code will create a new field called product_name
on the Customer
model, which will be populated with the value of the name
field on the Product
model.
Which method you use to access a field from a different model file depends on your specific needs. If you need to be able to update the value of the field, then you should use a Many2one field. If you only need to read the value of the field, then you can use a Related field.