
Learn how to use the reference field in Odoo 16 to create dynamic relationships across models. Explore examples and Python code for efficient customization.
In Odoo, the reference field is a powerful feature used to create dynamic relationships between records across different models. The reference field allows you to store a model name and a corresponding record ID, making it highly flexible for building relationships that aren't limited to a single model. In this blog, we'll explore how to implement and use a reference field in Odoo.
A reference field in Odoo allows users to link a record to any other record in any model. The field stores two pieces of information: the model name and the record's ID in that model. This is especially useful when you need to create a dynamic relationship, where the target model can vary from record to record.
To define a reference field, you can use the fields.Reference field type in your Odoo model. You must also provide a list of allowed models using the selection parameter.
Here's how you can define a reference field in a model in Odoo:
from odoo import models, fields
class CustomModel(models.Model):
_name = 'custom.model'
name = fields.Char(string="Name")
reference_field = fields.Reference(selection=[('res.partner', 'Partner'),
('res.users', 'User')],
string="Reference")
In this example:
Once a reference field is defined, users will be able to select the model and the record they want to reference. For example, you can reference a specific user or partner from the form view using this field. Odoo will automatically handle the display of the linked record's name in the user interface.
In your business logic, you may need to access the values of the reference field. Since the reference field stores both the model and the record ID, you can work with this data as shown below:
def check_reference(self):
for record in self:
model_name, record_id = record.reference_field.split(',')
referenced_record = self.env[model_name].browse(int(record_id))
# Do something with the referenced record
This code splits the reference field's value to extract the model and the record ID, which you can then use to browse the corresponding record in Odoo.
The reference field is an excellent solution for dynamic, multi-model relationships in Odoo. It provides flexibility by allowing you to link records across different models without hardcoding specific relationships. Whether you're working on custom apps or extending the functionality of existing modules, the reference field can be a valuable tool in your Odoo development toolkit.
Your email address will not be published. Required fields are marked *