Development Book V17: Related fields

In practical business scenarios, there are instances where we need to display the value of a field from a related model in the current model. In such cases, related fields come into play, and to implement this, we use the "related" attribute.

For example, consider a Many2one field named partner_id with a corresponding model (comodel) of res.partners. In this scenario, a related field named partner_name can be specified to display relevant information.

                partner_id = fields.Many2one('res.partners')
                    partner_name = fields.Char('Name', related="partner_id.name")
            

By default, the related fields are not stored in the database, and also it is read-only and not copied fields. If we want to store the field record in the database, we can use store = True attributes.

                
                    partner_name = fields.Char('Name', related="partner_id.name", store=True)
                
            

Reference Fields

In Odoo, reference fields provide a flexible way to create dynamic relationships between models. Unlike standard relational models, where related comodels are predefined, reference fields allow users to choose both the related model and a specific record from a selection list. Users first select the target model and then pick the desired record within that model. For example, a field named "reference" could be used to select Purchase Orders, Sale Orders, or Manufacturing Orders, providing a versatile approach to establishing connections between different models.

    reference_field = fields.Reference(selection='', string='field name')

For this, we use the selection parameter. We must assign the model and its name to this parameter.

For example:

    
        reference = fields.Reference(selection="[('sale.order', 'Sale Order'), ('purchase.order', ' Purchase Order')]", string="Reference")
Here, we can choose a Sale Order or Purchase Order, from the same field. Also possible to selection from a function.
reference = fields.Reference(selection="get_model")
@api.model
def get_model(self):
models = self.env['ir.model'].search([])
return [(model.model, model.name), for model in models]

Returned values must be a list.

whatsapp
location

Calicut

Cybrosys Technologies Pvt. Ltd.
Neospace, Kinfra Techno Park
Kakkancherry, Calicut
Kerala, India - 673635

location

Kochi

Cybrosys Technologies Pvt. Ltd.
1st Floor, Thapasya Building,
Infopark, Kakkanad,
Kochi, India - 682030.

location

Bangalore

Cybrosys Techno Solutions
The Estate, 8th Floor,
Dickenson Road,
Bangalore, India - 560042

Send Us A Message