Related Attribute in Odoo

TEAM-BASSAM
August 19, 2024
related attribute in odoo

There may be times when customizing in Odoo that we need to immediately display a field from a related model in another model. Odoo’s related attribute makes it simple for us to accomplish that.

The `related` attribute in Odoo is used to create a field in one model that is directly linked to a field in another model. This means that the field’s value is automatically fetched from the related model, without the need for manual updates.

Here’s a simple example where we are going to add a field name phone_number in the sale order form view after the field partner_id

sale_order.py

from odoo import api,models,fields


class SaleOrder(models.Model):
    _inherit = "sale.order"

    phone_number=fields.Char(string="Phone",related="partner_id.phone")

views.xml

<?xml version="1.0" encoding="utf-8" ?>
<odoo>
    <record id="view_order_form_inherit_phone" model="ir.ui.view">
        <field name="name">sale.order.form.inherit.phone</field>
        <field name="model">sale.order</field>
        <field name="inherit_id" ref="sale.view_order_form"/>
        <field name="arch" type="xml">
            <xpath expr="//field[@name='partner_id']" position="after">
                <field name="phone_number"/>
            </xpath>
        </field>
    </record>
</odoo>



In this example:

`phone_number`: This is the new field we are creating in the `sale. order` model.

`related=’partner_id.phone’`: This indicates that the value of the field phone_number should be fetched from the phone field of via the field partner_id (which is a many2one relationship to the `res. partner` model).

related-attributed-in-odoo
related-attributed-in-odoo

From the Screenshot, it’s quite clear that when selecting the customer the phone_number field gets automatically updated with the corresponding phone number of the customer.

Here when the Customer is ‘My Company’ the phone_number gets updated to 123456789, Similarly when the Customer is Administrator the phone number  automatically fetches the value 12345

Readonly by Default: Fields with the `related` attribute are readonly by default because their values are derived from another model.

The `related` attribute in Odoo is an also efficient way to link fields across models, enabling you to access and display related data effortlessly.

"Unlock the Full Potential of Your Business with Odoo ERP!"

"Get a Cost Estimate for Your ERP Project, Absolutely FREE!"

Get a Free Quote

Leave a Reply

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